Parse, Create & Manage JSON Data | Python for Beginners #18
Video: Parse, Create & Manage JSON Data | Python for Beginners #18 by Taught by Celeste AI - AI Coding Coach
Watch full page →Parse, Create & Manage JSON Data | Python for Beginners #18
JSON (JavaScript Object Notation) is a popular format for storing and exchanging data. In this tutorial, you will learn how to use Python's built-in json module to convert Python objects to JSON strings, parse JSON back to Python objects, and handle JSON data in files. Additionally, you'll see how to customize serialization for complex data types like datetime.
Code
import json
from datetime import datetime
# Sample Python dictionary
user = {
"name": "Alice",
"age": 25,
"member_since": datetime(2020, 5, 17)
}
# Custom serializer to handle datetime objects
def serialize(obj):
if isinstance(obj, datetime):
return obj.isoformat() # Convert datetime to ISO 8601 string
raise TypeError("Type not serializable")
# Convert Python dictionary to a pretty JSON string
json_string = json.dumps(user, indent=2, default=serialize)
print("JSON string with pretty print and datetime serialization:")
print(json_string)
# Parse JSON string back to Python dictionary
parsed = json.loads(json_string)
print("\nParsed Python object:")
print(parsed)
# Write JSON data to a file
with open("data.json", "w") as f:
json.dump(user, f, indent=2, default=serialize)
# Read JSON data from a file
with open("data.json", "r") as f:
loaded = json.load(f)
print("\nLoaded JSON data from file:")
print(loaded)
Key Points
- Use
json.dumps()to convert Python objects to JSON strings, with optional pretty printing usingindent. - Use
json.loads()to parse JSON strings back into Python objects. - Read and write JSON data to files using
json.load()andjson.dump(). - Customize serialization of non-standard types like
datetimeby providing adefaultfunction tojson.dump()orjson.dumps(). - Python’s
True,False, andNonemap to JSON’strue,false, andnullrespectively.