Parsing and Creating JSON
Python's json module has two main functions: loads() parses JSON into Python, dumps() converts Python to JSON.
import json
# Parse JSON string into Python dict
json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)
print(data["name"]) # Alice
Going the other direction:
# Convert Python dict to JSON string
data = {"name": "Alice", "age": 30}
json_string = json.dumps(data)
print(json_string) # '{"name": "Alice", "age": 30}'
The "s" in loads/dumps stands for "string." These work with text.
For files, use load() and dump() (without the "s"):
# Read from file
with open("data.json") as f:
data = json.load(f)
# Write to file
with open("data.json", "w") as f:
json.dump(data, f)
I explain these patterns in my JSON with Python course.