blog / guides

parsing JSON in Python: a practical beginner guide

by Luke published 8 min read

the short answer

Import Python’s built-in json module. json.loads() turns JSON text into dictionaries and lists, and json.load() does the same from an open file. Then read values with square brackets, like data["name"], or with .get() when a key might be missing.

To parse JSON in Python, import the built-in json module and pass your JSON text to json.loads(). You get back ordinary Python dictionaries and lists, and you read values from them with square brackets:

try it · python
import json

text = '{"name": "Sam", "age": 12}'
data = json.loads(text)
print(data["name"])
print(data["age"] + 1)
Sam
13

That covers most of what you will ever do with JSON. This guide explains the rest: what JSON is, how it maps onto Python, how to dig into nested data, read and write JSON files, and fix the errors beginners meet first. Every example runs in your browser.

What JSON is

JSON stands for JavaScript Object Notation. Despite the name, it is not tied to JavaScript. It is a way of writing data as plain text, so that any program in any language can read it. Websites send it, apps save settings in it, and most web services answer questions with it.

JSON is built from two shapes:

  • Objects: pairs of names and values inside curly brackets, like {"name": "Sam"}.
  • Arrays: lists of values inside square brackets, like ["cat", "fish"].

The values can be text, numbers, true, false, null, or more objects and arrays tucked inside.

Where you will meet JSON

  • Web services. Weather, maps and many other online services answer questions in JSON.
  • Settings files. Plenty of apps and tools keep their settings in .json files. VS Code is one.
  • Saved data. Small programs often save their data as JSON because it is easy to read back later.
  • Other languages. A Python program can read JSON written by a JavaScript program, and the other way round.

How JSON turns into Python

When you parse JSON, every part of it becomes a familiar Python value:

  • Object becomes a dictionary.
  • Array becomes a list.
  • Text becomes a string.
  • Whole numbers become int, and numbers with a decimal point become float.
  • true and false become True and False.
  • null becomes None.

You can see the change for yourself:

try it · python
import json

data = json.loads('{"done": true, "note": null, "tags": ["a", "b"]}')
print(data)
print(type(data))
{'done': True, 'note': None, 'tags': ['a', 'b']}
<class 'dict'>

Python prints dictionaries with single quotes. That is just how Python displays them. The JSON itself must still use double quotes.

Digging into nested data

Real JSON is usually layers of objects and arrays inside each other. Read it one layer at a time: square brackets with a name for an object, square brackets with a number for an array.

try it · python
import json

text = """
{
  "shop": "Corner Café",
  "orders": [
    {"item": "tea", "cups": 2},
    {"item": "coffee", "cups": 3},
    {"item": "cocoa", "cups": 1}
  ]
}
"""
data = json.loads(text)
print(data["shop"])
print(data["orders"][0]["item"])

total = 0
for order in data["orders"]:
    total = total + order["cups"]
print("Cups sold:", total)
Corner Café
tea
Cups sold: 6

data["orders"] is a list, so [0] picks its first item. That item is a dictionary, so ["item"] picks the value inside it. A loop visits every order in turn. If you get lost, print the part you are looking at, along with its type(), and you will see which kind of brackets come next.

When a key might be missing

Square brackets stop the program with a KeyError if the name is not there. When a value is optional, use .get() instead. It gives back None, or a fallback you choose:

try it · python
import json

user = json.loads('{"name": "Ola"}')
print(user.get("email"))
print(user.get("email", "no email given"))
None
no email given

Reading and writing JSON files

json.dump() writes Python data to a file as JSON, and json.load() reads it back. Notice there is no s on the end: these two work with files, not strings.

try it · python
import json

settings = {"theme": "dark", "volume": 7}

with open("settings.json", "w") as f:
    json.dump(settings, f)

with open("settings.json") as f:
    loaded = json.load(f)

print(loaded["theme"], loaded["volume"])
dark 7

The file only lasts while this example runs in your browser. On your own computer, settings.json would appear next to your program and stay there.

Turning Python back into JSON text

json.dumps(), with an s for string, does the opposite of loads(). Add indent=2 to spread the result over several lines:

try it · python
import json

pet = {"name": "Biscuit", "age": 3, "vaccinated": True}
print(json.dumps(pet))
print(json.dumps(pet, indent=2))
{"name": "Biscuit", "age": 3, "vaccinated": true}
{
  "name": "Biscuit",
  "age": 3,
  "vaccinated": true
}

Python’s True has gone back to JSON’s true, and the quotes are double again.

Handling broken JSON without crashing

JSON that comes from outside your program can be broken: a half-finished download, or a typo in a settings file someone edited by hand. Wrap the parse in try and except so your program can carry on and say what went wrong:

try it · python
import json

text = '{"name": "Sam"'
try:
    data = json.loads(text)
    print("Loaded", data["name"])
except json.JSONDecodeError as error:
    print("That JSON is broken:", error)
That JSON is broken: Expecting ',' delimiter: line 1 column 15 (char 14)

The message even says where the problem is. Column 15 is just past the last character, where Python expected either a comma or a closing curly bracket. Here the bracket is missing.

JSON from the web

Many websites offer data as JSON at a web address. Python fetches the text first, then parses it with json.loads() exactly as above. The fetching part needs an internet connection and a real address, so it is not shown here. Gwecode’s Python Level 2 has a lesson on it, called Talking to the web.

Common mistakes

Single quotes inside the JSON

try it · python
import json

json.loads("{'name': 'Sam'}")

This stops with json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1). JSON needs double quotes around every name and every piece of text. Python is relaxed about quotes, but JSON is not.

A comma after the last item

JSON does not allow a comma after the last item in an object or array, so {"a": 1,} fails with a JSONDecodeError too. Older versions of Python report it as the same double-quotes message as above, which is confusing. Newer versions say Illegal trailing comma instead.

Mixing up load and loads

json.loads() wants a string. Pass it an open file and you get TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper. Use json.load() for files and json.loads() for strings.

Numbers that arrive as text

Some JSON puts numbers inside quotes, like {"age": "12"}. Python then gives you the string "12", not the number 12, so data["age"] + 1 fails with a TypeError. Check what you have with type(), and convert it with int() or float() before doing sums.

Expecting attributes instead of keys

Parsed JSON gives you dictionaries, so data.name does not work. Write data["name"].

Treating Python’s printout as JSON

print(data) shows single quotes and True, which is not valid JSON. If you need to send or save JSON, make it with json.dumps(), not by printing.

A short exercise

Here is some JSON about a class quiz. Parse it, then print the name of the person with the highest score.

{"quiz": "Space", "results": [{"name": "Ava", "score": 7}, {"name": "Ben", "score": 9}, {"name": "Cal", "score": 8}]}

Your program should print Ben.

One possible answer

try it · python
import json

text = '{"quiz": "Space", "results": [{"name": "Ava", "score": 7}, {"name": "Ben", "score": 9}, {"name": "Cal", "score": 8}]}'
data = json.loads(text)

best = data["results"][0]
for person in data["results"]:
    if person["score"] > best["score"]:
        best = person
print(best["name"])

Your next step

JSON is where Python starts talking to the rest of the world. Gwecode’s Python Level 2 teaches it properly, along with dictionaries, files and fetching data from the web, and its level check has you build a budget tracker that saves its own data. Every lesson is free and runs in your browser. Create a free account to keep your progress, then try the JSON lesson below.

practise this · python · lessonJSON: data as textstart the lesson

questions

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

json.loads() reads JSON from a string. The s stands for string. json.load() reads it from an open file. They give back exactly the same kind of result.

Do I need to install anything to parse JSON?

No. The json module comes with Python. Just write import json at the top of your program.

Why does my JSON give an error about double quotes?

JSON only allows double quotes around text and key names. Single quotes, which Python itself is happy with, are not valid JSON.

How do I turn a Python dictionary into JSON?

Use json.dumps(). It gives back a JSON string. Add indent=2 to spread it over several lines so people can read it.

Is JSON the same as a Python dictionary?

They look alike, but JSON is text that any language can read, and a dictionary is a live Python value. JSON also writes true, false and null where Python writes True, False and None.

keep going.