The json Module

Python comes with a json module, so you do not need to install anything. It has four main functions. The ones ending in s work with strings; the others work with files.

FunctionWhat it does
json.loads(text)JSON string → Python object
json.dumps(obj)Python object → JSON string
json.load(file)Read JSON from a file
json.dump(obj, file)Write JSON to a file

Parse a JSON String

Python
import json

text = '{"name": "Emily", "age": 30, "active": true, "tags": ["admin"]}'
data = json.loads(text)

print(data["name"])     # Emily
print(data["active"])   # True  (JSON true becomes Python True)
print(type(data))       # <class 'dict'>

JSON types become Python types like this:

JSONPython
objectdict
arraylist
stringstr
numberint or float
true / falseTrue / False
nullNone

Convert Python to JSON

Python
import json

user = {"name": "Emily", "city": "London", "verified": True, "manager": None}

print(json.dumps(user))
# {"name": "Emily", "city": "London", "verified": true, "manager": null}

print(json.dumps(user, indent=2))   # pretty printed with 2 spaces

Read and Write JSON Files

Python
import json

# Read
with open("data.json", encoding="utf-8") as f:
    data = json.load(f)

# Change something
data["city"] = "Manchester"

# Write (pretty, and keep characters like é and 😊 as they are)
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

Loop Over the Items in a JSON File

Most JSON files hold a list of objects. After loading, it is a normal Python list of dictionaries:

Python
import json

with open("groups.json", "r", encoding="utf-8") as f:
    groups = json.load(f)

for group in groups:
    print(group["name"], len(group.get("members", [])))

group.get("members", []) returns an empty list instead of crashing with a KeyError when a record has no members field.

Read a JSON Lines File (One Object per Line)

Logs, exports and datasets often store one JSON object per line, in a .jsonl file. json.load cannot read the whole file: on a two-line file it stopped with Extra data: line 2 column 1 (char 57). Parse each line on its own with json.loads:

questions.jsonl
{"question": "What is JSON?", "answer": "A text format"}
{"question": "Is JSON a language?", "answer": "No"}
Python
import json

with open("questions.jsonl", "r", encoding="utf-8") as f:
    for line in f:
        if not line.strip():      # skip empty lines
            continue
        item = json.loads(line)
        print(item["question"])
Output
What is JSON?
Is JSON a language?

This reads one line at a time, so it works for files far bigger than your memory. More about the format in JSON Lines (JSONL).

Get JSON from an API

With only the standard library, open the URL and pass the response straight to json.load:

Python (no packages)
import json
import urllib.request

with urllib.request.urlopen("https://api.example.com/users/1") as response:
    user = json.load(response)

print(user["name"])

With the popular requests package (pip install requests), the response has a .json() method:

Python (requests)
import requests

response = requests.get("https://api.example.com/users/1", timeout=10)
response.raise_for_status()   # stop on 404, 500 and other errors
user = response.json()

If you get JSONDecodeError: Expecting value: line 1 column 1 (char 0), the server did not send JSON. When we pointed the same code at an HTML page, that is exactly the error it raised. Print the first part of the text and the status code to see what came back: an error page, a login page or an empty body.

Errors When Reading JSON Files

ErrorCause and fix
FileNotFoundError: [Errno 2] No such file or directoryThe path is wrong, or the script runs from another folder. Use a full path, or build it with pathlib.Path(__file__).parent / "data.json".
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81...On Windows, open() without an encoding uses an old code page. Always pass encoding="utf-8".
JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig)The file was saved with a byte order mark, common from Excel and Notepad. Open it with encoding="utf-8-sig".
JSONDecodeError: Expecting value: line 1 column 1 (char 0)The file is empty, or it is not JSON at all (for example an HTML page you downloaded by mistake). See JSONDecodeError: Expecting value for every cause.
JSONDecodeError: Extra data: line 2 column 1The file has one JSON object per line. That is JSON Lines: read it line by line with json.loads.

For other syntax errors, such as a missing comma or a trailing comma, see Common JSON Errors, or fix the file automatically with JSON Repair.

Handle Invalid JSON

If the text is not valid JSON, json.loads raises a json.JSONDecodeError that tells you the line and column.

Python
import json

try:
    data = json.loads('{"name": "Emily",}')   # trailing comma
except json.JSONDecodeError as error:
    print(f"Invalid JSON at line {error.lineno}, column {error.colno}: {error.msg}")

Tip: paste broken JSON into our JSON Repair tool to fix trailing commas, single quotes and Python values like True and None automatically.

Dates and Other Types

JSON only knows strings, numbers, booleans, null, lists and objects. Values like datetime, Decimal or sets raise TypeError: Object of type ... is not JSON serializable. The quick fix is default=str:

Python
import json
from datetime import datetime

event = {"title": "Launch", "starts": datetime(2026, 11, 8, 9, 30)}
print(json.dumps(event, default=str))
# {"title": "Launch", "starts": "2026-11-08 09:30:00"}

default=str is fine for logs, but it writes dates with a space instead of the ISO T and turns sets into text. The proper fix for each type is in Object of type X is not JSON serializable.

Useful Options

  • indent=2: pretty print with 2 spaces.
  • sort_keys=True: sort keys alphabetically.
  • ensure_ascii=False: keep non-English characters readable.
  • separators=(",", ":"): the smallest possible output (minified).

Want typed classes instead of dictionaries? Generate dataclasses or Pydantic models with our JSON to Python tool.

Save JSON as CSV

A list of dictionaries can be written to a CSV file with the built-in csv module, no extra packages needed:

Python
import csv, json

with open("users.json", encoding="utf-8") as f:
    rows = json.load(f)

with open("users.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())
    writer.writeheader()
    writer.writerows(rows)

For nested JSON and pandas, see How to Convert JSON to CSV in Python.

Frequently Asked Questions

What is the difference between json.load and json.loads?

json.load reads JSON from a file object, json.loads reads JSON from a string. The same goes for json.dump (to a file) and json.dumps (to a string).

How do I pretty print JSON in Python?

Use json.dumps(data, indent=2), or json.dump(data, file, indent=2) to write a nicely formatted file.

Why do I get 'Object of type datetime is not JSON serializable'?

JSON has no date type. Convert dates to strings first, for example with date.isoformat(), or pass default=str to json.dumps.

How do I keep non-English characters in the output?

Pass ensure_ascii=False to json.dumps, and open files with encoding='utf-8'.

Related Tools