Python JSON

The built-in json module lets Python convert between JSON text and its own data structures like dictionaries and lists.

What is JSON?

JSON, short for JavaScript Object Notation, is a lightweight text format used to store and exchange data, especially between web servers and applications. Python includes a module named json that turns JSON text into Python objects and Python objects back into JSON text, so you rarely have to parse it by hand.

Parsing JSON with loads()

Use json.loads() to read a JSON string and turn it into a Python value. A JSON object becomes a dictionary, a JSON array becomes a list, and the primitive types map to their Python equivalents. You can then access the data with normal dictionary and list syntax.

From JSON text to a Python dictionary

import json

text = '{"name": "Ravi", "age": 30, "skills": ["Python", "SQL"]}'
data = json.loads(text)

print(data["name"])      # Ravi
print(data["skills"][0]) # Python
print(type(data))        # <class 'dict'>

Producing JSON with dumps()

The reverse operation is json.dumps(), which serializes a Python object into a JSON-formatted string. This is what you use before sending data to an API or writing it to a file. Pass the indent argument to produce neatly formatted, human-readable output.

From a Python object to JSON text

import json

person = {
    "name": "Meena",
    "active": True,
    "roles": ["admin", "editor"]
}

print(json.dumps(person))
# {"name": "Meena", "active": true, "roles": ["admin", "editor"]}

print(json.dumps(person, indent=2, sort_keys=True))
Note: Notice how Python's True becomes JSON's true and None becomes null. The json module handles this translation automatically in both directions.
PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
True / Falsetrue / false
Nonenull
  • json.loads(s) parses a JSON string into a Python object.
  • json.dumps(obj) converts a Python object into a JSON string.
  • json.load(file) reads and parses JSON directly from a file object.
  • json.dump(obj, file) writes a Python object as JSON into a file object.
  • The indent argument controls pretty-printing, and sort_keys orders the keys alphabetically.

Reading and writing JSON files

import json

# Write a Python object to a file as JSON
config = {"theme": "dark", "volume": 8}
with open("config.json", "w") as f:
    json.dump(config, f, indent=2)

# Read it back into a dictionary
with open("config.json", "r") as f:
    loaded = json.load(f)
print(loaded["theme"])   # dark

Exercise: Python JSON

What does `json.dumps()` do?