Update tech_docs/python/json_python.md
This commit is contained in:
@@ -1,3 +1,139 @@
|
|||||||
|
Certainly! Understanding `json` module functions like `load`, `loads`, `dump`, and `dumps` is crucial for effective serialization and deserialization in Python. Here’s a breakdown of these functions and some helpful reminders:
|
||||||
|
|
||||||
|
### JSON Functions in Python
|
||||||
|
|
||||||
|
1. **`json.dump`**:
|
||||||
|
- Serializes a Python object to a JSON-formatted stream (usually a file).
|
||||||
|
- Takes a file-like object as an argument.
|
||||||
|
|
||||||
|
**Syntax:**
|
||||||
|
```python
|
||||||
|
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```python
|
||||||
|
import json
|
||||||
|
|
||||||
|
person = {"name": "Alice", "age": 30}
|
||||||
|
|
||||||
|
with open("person.json", "w") as file:
|
||||||
|
json.dump(person, file)
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **`json.dumps`**:
|
||||||
|
- Serializes a Python object to a JSON-formatted string.
|
||||||
|
- Useful for sending JSON data over a network or saving it in a string format.
|
||||||
|
|
||||||
|
**Syntax:**
|
||||||
|
```python
|
||||||
|
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```python
|
||||||
|
person = {"name": "Alice", "age": 30}
|
||||||
|
person_json = json.dumps(person)
|
||||||
|
print(person_json) # Output: {"name": "Alice", "age": 30}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **`json.load`**:
|
||||||
|
- Deserializes a JSON-formatted stream (usually a file) to a Python object.
|
||||||
|
- Takes a file-like object as an argument.
|
||||||
|
|
||||||
|
**Syntax:**
|
||||||
|
```python
|
||||||
|
json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```python
|
||||||
|
with open("person.json", "r") as file:
|
||||||
|
person = json.load(file)
|
||||||
|
print(person) # Output: {'name': 'Alice', 'age': 30}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **`json.loads`**:
|
||||||
|
- Deserializes a JSON-formatted string to a Python object.
|
||||||
|
|
||||||
|
**Syntax:**
|
||||||
|
```python
|
||||||
|
json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```python
|
||||||
|
person_json = '{"name": "Alice", "age": 30}'
|
||||||
|
person = json.loads(person_json)
|
||||||
|
print(person) # Output: {'name': 'Alice', 'age': 30}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Helpful Reminders
|
||||||
|
|
||||||
|
1. **File Handling:**
|
||||||
|
- Always open files in the correct mode: `w` for writing, `r` for reading.
|
||||||
|
- Use `with` statements to handle files to ensure they are properly closed after use.
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```python
|
||||||
|
with open("data.json", "w") as file:
|
||||||
|
json.dump(data, file)
|
||||||
|
|
||||||
|
with open("data.json", "r") as file:
|
||||||
|
data = json.load(file)
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Indentation and Formatting:**
|
||||||
|
- Use the `indent` parameter in `dumps` and `dump` to format JSON output for better readability.
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```python
|
||||||
|
person_json = json.dumps(person, indent=4)
|
||||||
|
print(person_json)
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Custom Serialization:**
|
||||||
|
- You can define custom serialization for objects that aren’t natively serializable by JSON using the `default` parameter in `dumps` or `dump`.
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```python
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
def default_serializer(obj):
|
||||||
|
if isinstance(obj, datetime):
|
||||||
|
return obj.isoformat()
|
||||||
|
raise TypeError(f"Type {type(obj)} not serializable")
|
||||||
|
|
||||||
|
data = {"name": "Alice", "timestamp": datetime.now()}
|
||||||
|
json_str = json.dumps(data, default=default_serializer)
|
||||||
|
print(json_str)
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Error Handling:**
|
||||||
|
- Handle exceptions such as `json.JSONDecodeError` to catch errors during deserialization.
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```python
|
||||||
|
import json
|
||||||
|
|
||||||
|
json_str = '{"name": "Alice", "age": 30' # Malformed JSON
|
||||||
|
|
||||||
|
try:
|
||||||
|
person = json.loads(json_str)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
print(f"JSON decode error: {e}")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Summary
|
||||||
|
|
||||||
|
- **`dump`** and **`dumps`**: Used for serialization. `dump` writes to a file, and `dumps` returns a string.
|
||||||
|
- **`load`** and **`loads`**: Used for deserialization. `load` reads from a file, and `loads` parses a string.
|
||||||
|
|
||||||
|
These tools and practices will help you efficiently work with JSON data in Python.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
Sure! Let's focus on the Python implementation of serialization and deserialization, illustrating the process with detailed examples.
|
Sure! Let's focus on the Python implementation of serialization and deserialization, illustrating the process with detailed examples.
|
||||||
|
|
||||||
### Serialization
|
### Serialization
|
||||||
|
|||||||
Reference in New Issue
Block a user