Dictionary Serialization: JSON
Python Dictionary का String में Best Representation JSON है। आप Dictionary को String में Convert करने के लिए json.dumps(dict) का उपयोग कर सकते हैं। और String से Dictionary वापस पाने के लिए json.loads(string) का उपयोग कर सकते हैं।
उदाहरण
>>> import json
>>> d = {'id': 15, 'name': 'John'}
>>> x = json.dumps(d)
>>> print(x)
{"id": 15, "name": "John"}
>>> print(json.loads(x))
{'id': 15, 'name': 'John'}
यह Python Dictionaries को Serialize और Deserialize करने का सबसे आसान और तेज़ तरीका है।
Advanced JSON Options:
import json
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Pretty Print
json.dumps(data, indent=2)
# {
# "name": "Alice",
# "age": 30,
# "city": "New York"
# }
# Sort Keys
json.dumps(data, sort_keys=True)
# Custom Separators
json.dumps(data, separators=(',', ':'))
# Non-ASCII Characters
json.dumps({'city': '北京'}, ensure_ascii=False)
# '{"city": "北京"}'
Alternative: pickle (Python-specific, Not Human-readable):
import pickle
data = {'id': 15, 'name': 'John'}
serialized = pickle.dumps(data)
deserialized = pickle.loads(serialized)
# Warning: pickle Untrusted Data के लिए Unsafe है!
Comparison:
| Format | Human Readable | Cross-language | Security |
|---|---|---|---|
| JSON | Yes | Yes | Safe |
| Pickle | No | Python Only | Unsafe (Code Exec) |
| YAML | Yes | Yes | Safe (with SafeLoader) |