Mastering Python's JSON Module ๐
Mastering Python's JSON Module ๐
The json module in Python is essential for converting JSON data to Python objects and vice versa, handling formatting, and managing JSON files seamlessly.
1. JSON String ↔ Python Object
import json
data = '{"name": "John", "age": 30, "languages": ["Python", "JavaScript"]}'
obj = json.loads(data)
print(obj, type(obj)) # {'name': 'John', 'age': 30, 'languages': ['Python', 'JavaScript']}
s = json.dumps(obj)
print(s, type(s)) # String
2. Pretty Printing with Indentation
import json
obj = {"name": "Jane", "age": 25, "city": "New York"}
pretty = json.dumps(obj, indent=4, ensure_ascii=False)
print(pretty)
# {
# "name": "Jane",
# "age": 25,
# "city": "New York"
# }
3. Reading and Writing JSON Files
import json
config = {"debug": True, "version": 1.2}
with open('config.json', 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2, ensure_ascii=False)
with open('config.json', encoding='utf-8') as f:
loaded = json.load(f)
print(loaded, type(loaded))
4. Exception Handling and Validation
import json
def safe_load(json_str):
try:
return json.loads(json_str)
except json.JSONDecodeError as e:
print("Parsing error:", e)
return None
print(safe_load('{"bad json": }')) # None
Summary
- Convert JSON strings and Python objects using
loadsanddumps. - Create readable JSON with
indentandensure_ascii=False. - Use
loadanddumpfor JSON file operations. - Handle JSON parsing errors effectively with
JSONDecodeError.
Comments
Post a Comment