JSON with Python: Reading & Writing (With Examples)

JSON (JavaScript Object Notation) is the standard way to exchange structured data in web applications, REST APIs, and configuration files. Python’s built-in json module makes it trivial to serialize Python objects to JSON strings and deserialize JSON back into Python objects, handling the mapping between types automatically.

JSON is text-based, human-readable, and widely supported across all programming languages, making it a better choice than XML for most use cases. The syntax comes from JavaScript but works independently of any language.

JSON with Python

Working with JSON in Python uses two main concepts:

  • Serialization: Converting a Python object to a JSON string. This is encoding.
  • Deserialization: Converting a JSON string back to a Python object. This is decoding.

Python’s json module handles both directions automatically, translating between Python and JSON types. Start by importing it:

import json

Serialization

Serialization converts Python data to a JSON string. The JSON encoder supports these Python types:

Python JSON
dict object
list, tuple array
str string
int, float number
True true
False false
None null

The JSON module has two methods for serialization: dumps() and dump().

dumps()

The dumps() method takes a Python object and returns a JSON-formatted string. The name stands for “dump string.”

import json

dc = { "name" : "John", "age" : 25, "location" : "New York"}
js = json.dumps(dc)
print(js)

Output:

{"name": "John", "age": 25, "location": "New York"}

Notice that dumps() returns a str, not bytes. Tuples are automatically converted to JSON arrays:

import json

tp = (1, 2, 3, 4, 5)
js = json.dumps(tp)
print(js)

Output:

[1, 2, 3, 4, 5]

When you deserialize this JSON back to Python, the array becomes a list, not a tuple. That round-trip difference matters if your code later checks type(obj) is tuple.

Use sort_keys=True to sort dictionary keys and indent=N to pretty-print with N spaces per level:

import json

dc = { "name" : "John", "age" : 25, "location" : "New York"}
js = json.dumps(dc, sort_keys=True, indent=3)
print(js)

Output:

{
   "age": 25,
   "location": "New York",
   "name": "John"
}

dump()

The dump() method serializes an object to JSON and writes it directly to a file object. Unlike dumps(), it doesn’t return a string.

import json

dc = { "name" : "John", "age" : 25, "location" : "New York"}
with open("newfile.json", "w") as file:
    json.dump(dc, file, sort_keys=True, indent=3)

The resulting newfile.json file contains:

{
   "age": 25,
   "location": "New York",
   "name": "John"
}

Notice: pass the file object (not the filename) as the second argument. Using with ensures the file is properly closed and data is flushed to disk.

Deserialization

Deserialization reverses the process: it converts a JSON string or file back into Python objects using the JSON type mapping (array becomes list, null becomes None, etc.).

loads()

The loads() method takes a JSON string and returns a Python object. The name stands for “load string.”

import json

js = '{ "name" : "John", "age" : 25, "location" : "New York"}'
dc = json.loads(js)
print(dc)

Output:

{'name': 'John', 'age': 25, 'location': 'New York'}

If the JSON string is invalid (for example, using single quotes instead of double quotes), loads() raises a JSONDecodeError:

import json

js = "{'name': 'John'}"  # Invalid: single quotes
dc = json.loads(js)

Python raises:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

load()

The load() method reads JSON from a file object and returns a Python object. This is the file equivalent of loads().

import json

with open("newfile.json", "r") as file:
    data = json.load(file)
    print(data)

Output:

{'age': 25, 'location': 'New York', 'name': 'John'}

The with statement automatically closes the file when done.

Custom Objects

By default, the JSON encoder doesn’t know how to serialize custom class instances:

import json

class DemoClass:
    def __init__(self, val1, val2):
        self.val1 = val1
        self.val2 = val2

obj1 = DemoClass("Value1", "Value2")
js = json.dumps(obj1)

Python raises:

TypeError: Object of type DemoClass is not JSON serializable

There are two main solutions:

Option 1: Use the __dict__ attribute — This works for simple objects with only serializable attributes:

import json

class DemoClass:
    def __init__(self, val1, val2):
        self.val1 = val1
        self.val2 = val2

obj1 = DemoClass("Value1", "Value2")
js = json.dumps(obj1.__dict__)
print(js)

Output:

{"val1": "Value1", "val2": "Value2"}

Option 2: Use the default parameter — This is more flexible and works with any object type. Pass a function that converts your object to something JSON-serializable:

import json
from datetime import datetime

def serialize_datetime(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Object of type {type(obj)} is not JSON serializable")

data = {"timestamp": datetime.now()}
js = json.dumps(data, default=serialize_datetime)
print(js)

The default parameter also accepts built-in functions like str to convert unknowns to strings. For deserialization, use object_hook to customize how objects are reconstructed from dictionaries.

Common Gotchas

Non-string dictionary keys become strings. JSON only allows string keys, so Python dicts with integer keys get converted:

import json

data = {1: "one", 2: "two"}
js = json.dumps(data)
restored = json.loads(js)
print(restored)
# {'1': 'one', '2': 'two'} — keys are now strings
print(list(restored.keys()))
# ['1', '2']

If you need integer keys, store them differently or use a custom object_hook on deserialization.

Encoding matters when reading and writing files. Always specify encoding="utf-8" when opening JSON files to avoid platform-dependent defaults. The dump() and load() methods don’t handle this themselves—the file object does.

For the complete list of parameters, supported options, and edge cases, refer to the official Python JSON documentation.

Conclusion

Python’s json module handles serialization and deserialization with just a few methods, automatically converting between Python and JSON types. For most use cases, dumps() and loads() (for strings) or dump() and load() (for files) are all you need. When you have custom objects, the default parameter gives you fine-grained control without resorting to __dict__ hacks.

Your JSON will typically end up in a file or sent over HTTP, so reading and writing files in Python is a natural next read.

What’s your most common use case for JSON—storing config files, exchanging API data, or something else?