JSON Copilot

How do I read JSON in Python?

Advanced Topics

Python reads JSON with the built-in json module. Use json.load() to read from a file and json.loads() to parse a string. JSON objects become Python dictionaries and JSON arrays become lists.

import json

# Read from a file
with open("data.json") as f:
    data = json.load(f)

# Parse from a string
data = json.loads('{ "name": "Ada", "age": 36 }')
print(data["name"])  # Ada

Writing JSON back out

# Object -> string (pretty-printed)
text = json.dumps(data, indent=2)

# Write to a file
with open("out.json", "w") as f:
    json.dump(data, f, indent=2)

Tip: remember the difference. load/dump work with files, while loads/dumps (with an "s") work with strings.

Invalid JSON raises json.JSONDecodeError, so check your data in the validator first. Using JavaScript instead? See parsing JSON in JavaScript.

Still Have Questions?

Check out our other FAQ topics or return to the JSON Copilot app