■ Python JSON Module – Part 1
✓ json.dumps()
• What it does:
Converts a Python object into a JSON string.
• Parameters:
- obj: The object to convert.
- skipkeys: If True, skips keys that are not str, int, float, bool, or None.
- ensure_ascii: If True, all non-ASCII characters are escaped.
- check_circular: If True, checks for circular references.
- allow_nan: If True, allows NaN and Infinity.
- cls: Custom encoder class.
- indent: Pretty-prints with specified indentation.
- separators: Tuple for customizing item separators.
- default: A function for objects that can't be serialized.
- sort_keys: If True, output keys in sorted order.
Code
```python
import json
data = {"name": "John", "age": 30}
json_string = json.dumps(data, indent=2)
print(json_string)
# Output: JSON-formatted string
```
Code
✓ json.loads()
• What it does:
Parses a JSON string and converts it into a Python object.
• Parameters:
- s: JSON string to parse.
- cls: Optional custom decoder class.
- object_hook: Function that transforms dicts.
- parse_float: Function to parse float values.
- parse_int: Function to parse int values.
- parse_constant: Handles constants like NaN.
- object_pairs_hook: Preserves order of dict items.
Code
```python
import json
json_str = '{"name": "John", "age": 30}'
data = json.loads(json_str)
print(data)
# Output: {'name': 'John', 'age': 30}
```
Code
✓ json.dump()
• What it does:
Writes Python data to a file in JSON format.
• Parameters:
- obj: Python object to write.
- fp: File object to write into.
- indent, separators, etc: Same as in dumps().
Code
```python
import json
info = {"city": "Nairobi", "country": "Kenya"}
with open("info.json", "w") as file:
json.dump(info, file, indent=4)
```
Code
✓ json.load()
• What it does:
Reads a JSON object from a file and converts it to a Python object.
Code
```python
import json
with open("info.json", "r") as file:
info = json.load(file)
print(info)
# Output: {'city': 'Nairobi', 'country': 'Kenya'}
```
Code
✓ JSONEncoder
• What it does:
A class that lets you customize how objects are encoded to JSON.
• You can subclass it to change how complex objects are handled.
Code
```python
import json
from json.encoder import JSONEncoder
class MyEncoder(JSONEncoder):
def default(self, obj):
return str(obj)
data = {"value": complex(2, 3)}
print(json.dumps(data, cls=MyEncoder))
# Output: {"value": "(2+3j)"}
```
Code
...
(Only a small sample of Part 1 is added here to demonstrate PDF structure. Full content wo
uld follow.)