TExcelTAD
Home › Python › Python JSON

Python JSON

JSON (JavaScript Object Notation) is the most common text format for exchanging data — web APIs, configuration files and log records all use it. Python's built-in json module converts between JSON text and Python objects.

json
{
  "name": "Ngoc",
  "age": 28,
  "languages": ["Python", "SQL"],
  "remote": true,
  "manager": null
}

Type mapping

JSON Python
object {} dict
array [] list (tuples are written as arrays too)
string str
number (integer) int
number (fraction) float
true / false True / False
null None

From JSON text to Python: json.loads()

loads ("load string") parses JSON text and returns Python objects:

python · try it yourself
import json

text = '{"name": "Ngoc", "age": 28, "languages": ["Python", "SQL"], "remote": true, "manager": null}'
person = json.loads(text)

print(type(person).__name__)
print(person["name"], person["age"] + 1)
print(person["languages"][0])
print(person["remote"], person["manager"])
dict
Ngoc 29
Python
True None

From Python to JSON text: json.dumps()

dumps ("dump string") goes the other way:

python · try it yourself
import json

order = {
    "id": 1042,
    "items": ("pen", "notebook"),
    "paid": False,
    "coupon": None,
    "total": 7.5,
}
print(json.dumps(order))
{"id": 1042, "items": ["pen", "notebook"], "paid": false, "coupon": null, "total": 7.5}

Notice the conversions: the tuple became an array, False became false and None became null.

Making JSON readable

dumps has options for pretty output:

Option Effect
indent=2 multi-line output, indented by 2 spaces
sort_keys=True keys in alphabetical order
separators=(",", ":") most compact output
ensure_ascii=False keep non-ASCII characters like ă as-is
python · try it yourself
import json

city = {"name": "Đà Lạt", "altitude_m": 1500, "tags": ["flowers", "cool"]}
print(json.dumps(city, indent=2, sort_keys=True, ensure_ascii=False))
print(json.dumps(city))
print(json.dumps([1, 2, {"a": 3}], separators=(",", ":")))
{
  "altitude_m": 1500,
  "name": "Đà Lạt",
  "tags": [
    "flowers",
    "cool"
  ]
}
{"name": "\u0110\u00e0 L\u1ea1t", "altitude_m": 1500, "tags": ["flowers", "cool"]}
[1,2,{"a":3}]

Without ensure_ascii=False, non-ASCII characters are written as \u escape codes. Both forms are valid JSON.

Reading and writing files

json.dump() and json.load() (no s) work directly with file objects:

python
import json

settings = {"theme": "dark", "font_size": 14}

with open("settings.json", "w", encoding="utf-8") as f:
    json.dump(settings, f, indent=2)

with open("settings.json", encoding="utf-8") as f:
    loaded = json.load(f)
Function Input Output
json.loads(text) string Python object
json.dumps(obj) Python object string
json.load(file) file Python object
json.dump(obj, file) Python object + file writes to the file

Handling errors and unsupported types

Invalid JSON raises json.JSONDecodeError (a subclass of ValueError). Objects JSON doesn't know about, such as dates or sets, raise TypeError — unless you supply a default function that converts them:

python · try it yourself
import json
from datetime import date

try:
    json.loads("{'single': 'quotes'}")       # JSON requires double quotes
except json.JSONDecodeError as err:
    print("Bad JSON:", err.msg)

event = {"title": "Launch", "on": date(2025, 9, 1), "tags": {"web"}}
try:
    json.dumps(event)
except TypeError as err:
    print("TypeError:", err)

def to_jsonable(obj):
    if isinstance(obj, date):
        return obj.isoformat()
    if isinstance(obj, set):
        return sorted(obj)
    raise TypeError(f"cannot serialise {type(obj).__name__}")

print(json.dumps(event, default=to_jsonable))
Bad JSON: Expecting property name enclosed in double quotes
TypeError: Object of type date is not JSON serializable
{"title": "Launch", "on": "2025-09-01", "tags": ["web"]}

Working with API-style data

JSON from web services is usually nested. Once loaded, it's just dicts and lists:

python · try it yourself
import json

response = """
{"results": [
  {"city": "Hanoi", "temp": 31.2},
  {"city": "Sapa", "temp": 18.4},
  {"city": "Hue", "temp": 29.0}
], "unit": "C"}
"""
data = json.loads(response)
for r in sorted(data["results"], key=lambda r: r["temp"]):
    print(f"{r['city']:<6} {r['temp']:>5.1f} °{data['unit']}")
Sapa    18.4 °C
Hue     29.0 °C
Hanoi   31.2 °C

Tip: JSON keys are always strings. json.loads(json.dumps({1: "a"})) gives back {"1": "a"} — the integer key became a string.

Test yourself

Which function converts a JSON string into a Python object?

  1. json.dumps()
  2. json.loads()
  3. json.parse()
  4. json.dump()

What does Python's None become in JSON?

  1. None
  2. ""
  3. null
  4. undefined

Which dumps argument produces nicely indented, multi-line output?

  1. pretty=True
  2. indent=2
  3. format="pretty"
  4. lines=True