JSON

Working with JSON

JSON is a lightweight, human-readable format for storing and exchanging data. The built-in JSON module makes it simple to read and write JSON files. Set it up with:

import json

With JSON, JSON objects become Python dictionaries, JSON arrays become Python lists.

Reading JSON Files

Load a JSON file into a Python variable:

with open('file.json') as f:
    data = json.load(f)  # Converts JSON into Python dict/list

Here is an example of reading a JSON file.

{
  "name": "Adam",
  "age": 34,
  "hobbies": ["reading", "carpentry"]
}
print(data['name'])      # Output: Adam
print(data['hobbies'][1])  # Output: carpentry

Writing JSON Files

Convert Python objects to JSON and write them to a file. json.dump() writes a Python object directly to a JSON file.

to_save = {
    "name": "Bob",
    "age": 25,
    "hobbies": ["gaming", "coding"]
}
with open('output.json', 'w') as f:
    json.dump(to_save, f)

Extra Tips and Tricks

Pretty Printing JSON

with open('output.json', 'w') as f:
    json.dump(to_save, f, indent=4)
# Makes the file human-readable with 4-space indentation.

Converting JSON Strings

From string to Python object:

json_string = '{"key": "value"}'
data = json.loads(json_string)

From Python object to JSON string:

json_str = json.dumps(data)

Handling Unicode and Encoding

If your data includes non-ASCII characters:

json.dump(data, f, ensure_ascii=False, indent=4)

Common Errors

Error Meaning Fix
JSONDecodeError JSON file is not properly formatted Use a linter like JSON lint
TypeError: Object of type X is not JSON serializable You're trying to save an unsupported object (e.g., a datetime or set) Convert to a supported type like string or list first

Python to JSON Type Mapping

Python Type JSON Equivalent
dict Object
list Array
str String
int, float Number
True/False true/false
None null