Back to Blog

Parse, Create & Manage JSON Data | Python for Beginners #18

Sandy LaneSandy Lane

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 using indent.
  • Use json.loads() to parse JSON strings back into Python objects.
  • Read and write JSON data to files using json.load() and json.dump().
  • Customize serialization of non-standard types like datetime by providing a default function to json.dump() or json.dumps().
  • Python’s True, False, and None map to JSON’s true, false, and null respectively.