FormatterHQ

Data formats

How to Parse JSON in Python (json.loads, json.load & requests)

Parse JSON in Python the right way — json.loads for strings, json.load for files, response.json() for APIs — plus the boolean gotcha, error handling and writing JSON back out.

Published 6 min read

Parsing JSON in Python means turning a JSON string (from a file, an API, or a database) into native Python objects you can work with — dictionaries, lists, strings and numbers. Python ships with a built-in json module, so you rarely need a third-party library. This guide covers the three cases you will actually hit: a JSON string, a JSON file, and a JSON API response, plus the gotchas and how to write JSON back out.

Before parsing data you do not control, it helps to eyeball it: paste it into the JSON formatter to read the structure, or the validator to confirm it is well-formed.

Parse a JSON string with json.loads()

Use json.loads() (“load string”) to parse a string. It returns a Python object — a JSON object becomes a dict, an array becomes a list:

import json

text = '{"name": "Ada", "roles": ["admin", "author"], "active": true}'
data = json.loads(text)

print(data["name"])       # Ada
print(data["roles"][0])   # admin
print(type(data))         # <class 'dict'>

How JSON maps to Python types

JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
true / falseTrue / False
nullNone

The boolean and null mapping is the classic gotcha: JSON uses lowercase true/false/null, but Python uses True/False/None. If you try to hand-write a Python dict as JSON text you will hit this — let the module do the conversion for you.

Parse a JSON file with json.load()

For a file, use json.load() (no “s”) with an open file handle. It reads and parses in one step:

import json

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

print(len(data["items"]))

Rule of thumb: loads takes a string, load takes a file-like object.

Parse a JSON API response

With the popular requests library, call .json() on the response — it parses the body for you:

import requests

resp = requests.get("https://api.example.com/users/1")
resp.raise_for_status()          # fail loudly on 4xx/5xx
user = resp.json()               # dict

print(user["email"])

Using only the standard library (urllib), you read the body and parse it yourself:

import json, urllib.request

with urllib.request.urlopen("https://api.example.com/users/1") as r:
    user = json.loads(r.read().decode("utf-8"))

Need to pull one field out of a deeply nested response? A JSONPath expression (see our path finder) is often cleaner than chaining ["a"]["b"][0] by hand.

Handle parse errors

If the text is not valid JSON, json.loads() raises json.JSONDecodeError. Catch it rather than letting it crash — and remember a very common cause is that the server returned HTML (an error page) instead of JSON:

import json

try:
    data = json.loads(text)
except json.JSONDecodeError as e:
    print(f"Invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}")

When you are staring at a payload that will not parse, paste it into the JSON validator to get the exact position of the problem, then the JSON fixer if it needs repair.

Write JSON back out

The reverse of parsing is serialising. Use json.dumps() for a string and json.dump() for a file:

import json

payload = {"name": "Ada", "active": True, "scores": [1, 2, 3]}

# Compact (good for sending over the wire)
wire = json.dumps(payload)

# Pretty, with sorted keys (good for files and diffs)
pretty = json.dumps(payload, indent=2, sort_keys=True)

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

Two useful flags: indent controls pretty-printing (compact with no indent for sending over the wire, indented for files and diffs), and ensure_ascii=False keeps non-ASCII characters (like accents or emoji) readable instead of escaping them. You can check the result in the formatter or minify it with JSON minify.

Access nested values without crashing

Once parsed, a payload is just nested dicts and lists, so you index into it normally. The risk is a KeyError or TypeError when a key is missing or null. Use dict.get() with a default, and guard lists before indexing:

user = json.loads(text)

# Safe: returns None (or a default) instead of raising
city = user.get("profile", {}).get("city", "unknown")

roles = user.get("roles") or []
first_role = roles[0] if roles else None

For values buried several levels deep, a JSONPath expression is often clearer than a chain of ["a"]["b"][0] — build and test the path against a sample in the JSON path finder, then apply it in code.

Parse newline-delimited JSON (JSONL)

Large datasets and log files often use JSON Lines (.jsonl) — one JSON object per line — so you can stream records without loading the whole file into memory. Parse it line by line, not with a single json.load():

import json

records = []
with open("events.jsonl", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if line:                      # skip blank lines
            records.append(json.loads(line))

print(len(records))

This streaming approach keeps memory flat even for multi-gigabyte files, because only one record is in memory at a time.

Turn JSON into typed Python

For anything beyond a quick script, you probably want typed models rather than raw dicts. Generate a starting point automatically with the JSON to Python tool — paste a sample payload and it produces dataclasses or TypedDict definitions you can refine. The same idea works server-side: see generating a Laravel model and migration from JSON.

Pretty-print JSON from the command line

You do not even need a script to format a JSON file — the json module ships a command-line tool. Pipe or point it at a file to indent and sort keys:

# Pretty-print a file
python -m json.tool data.json

# Pretty-print from a pipe, sorting keys
curl -s https://api.example.com/users/1 | python -m json.tool --sort-keys

This is handy for quickly inspecting an API response in the terminal. For anything more involved — fixing a broken payload, diffing two documents, or converting formats — the browser tools are faster, and your data stays on your machine.

Common mistakes to avoid

  • Mixing up load and loads — passing a string to json.load() raises AttributeError: 'str' object has no attribute 'read'.
  • Double-parsing — calling json.loads() on something that is already a dict (for example the result of response.json()) raises TypeError.
  • Assuming a key exists — use .get() for optional fields so a missing key returns None instead of raising KeyError.
  • Forgetting encoding — open files with encoding="utf-8" so non-ASCII text parses correctly on every platform.
  • Trusting the content type — an API can return HTTP 200 with an HTML error body; always be ready to catch JSONDecodeError.

Key takeaways

  • json.loads() parses a string; json.load() parses a file.
  • With requests, use response.json().
  • JSON true/false/null become Python True/False/None.
  • Catch json.JSONDecodeError — a frequent cause is HTML returned instead of JSON.
  • Serialise with json.dumps()/json.dump(); use indent and ensure_ascii=False as needed.
  • JSON
  • Python
  • Parsing
  • APIs

Frequently asked questions

What is the difference between json.loads and json.load in Python?
json.loads() parses a JSON string (the “s” is for string). json.load() parses from a file-like object. Both return native Python objects — a JSON object becomes a dict, an array becomes a list.
How do I parse a JSON API response in Python?
With the requests library, call .json() on the response object: requests.get(url).json(). With the standard library, read the body and pass it to json.loads().
Why does json.loads give a JSONDecodeError?
The text is not valid JSON. A very common cause when calling an API is that the server returned an HTML error page instead of JSON. Catch json.JSONDecodeError and inspect e.lineno/e.colno, or paste the payload into the JSON validator to find the exact position.
How do I convert a Python dict to JSON?
Use json.dumps(obj) for a string or json.dump(obj, file) to write a file. Add indent=2 to pretty-print and ensure_ascii=False to keep non-ASCII characters readable.
Do I need a library to parse JSON in Python?
No. The built-in json module handles parsing and serialising. You only need a third-party package like requests for the HTTP call itself, not for the JSON.

Tools used in this guide