How do I parse and generate JSON in Python?
· Category: Python Programming
Short answer
Use the json module to convert between Python objects and JSON strings. json.load() and json.loads() parse JSON into Python, while json.dump() and json.dumps() serialize Python objects into JSON.
Steps
- Import
json. - Parse JSON with
json.loads(text)orjson.load(file). - Generate JSON with
json.dumps(obj)orjson.dump(obj, file).
import json
# Parse JSON string
data = json.loads('{"name": "Alice", "age": 30}')
print(data["name"])
# Generate JSON string
payload = {"status": "ok", "count": 42}
json_text = json.dumps(payload, indent=2)
print(json_text)
Tips
- Use
indentandsort_keysinjson.dumps()to produce human-readable output. - Custom objects can be serialized by providing a
defaultfunction. - Use
object_hookorjson.JSONDecodersubclasses for custom deserialization.
# Custom serialization
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def encode_point(obj):
if isinstance(obj, Point):
return {"x": obj.x, "y": obj.y}
raise TypeError
p = Point(1, 2)
print(json.dumps(p, default=encode_point))
Common issues
- JSON keys must be strings; Python converts non-string dict keys to strings.
- Sets, tuples, and custom objects are not JSON-serializable by default.
json.load()expects a text file opened with the correct encoding, not binary mode.