Python JSON
Practical Python Practical Python Practical example

Working with JSON in Python

1Python JSON: overview

JSON is a plain-text format for structured data, and Python's built-in json module converts JSON text into dictionaries and lists — and back again.

GoalBy the end you can turn JSON text into Python data with json.loads(), turn Python data into JSON with json.dumps(), pretty-print it with indent, dig into nested JSON safely, and save and load a JSON file.

Before this lesson: Python Dictionaries, Python File Handling

2Python JSON: diagram

Working with JSON in Pythonjson.loads(text)JSON textPython dict"name": "Asha"'name': 'Asha'"age": 21'age': 21"member": true'member': True"coupon": null'coupon': None"tags": ["new", "vip"]'tags': ['new', 'vip']"address": {...}'address': {...}true/false -> True/False, null -> None, object -> dict, array -> list
json.loads() reads JSON text and builds the matching Python objects. Most values look the same, but true, false and null become True, False and None. json.dumps() does the reverse.

3Python JSON: explained step by step

JSON (JavaScript Object Notation) is the most common way for programs to swap data: web APIs answer in JSON, apps save settings in it, and many tools export it. It looks a lot like Python, which makes it easy to read — but until you convert it, JSON is just text: one long string.

JSON text to Python: json.loads()

json.loads() ("load string") parses JSON text and gives you ordinary Python objects:

  • a JSON object {...} becomes a dict
  • a JSON array [...] becomes a list
  • true / false become True / False, and null becomes None
  • strings and numbers stay strings and numbers
Python
import json

text = '{"name": "Asha", "age": 21, "member": true, "coupon": null}'
user = json.loads(text)
print(user)
print(type(user).__name__, user["member"], user["coupon"])

Python to JSON text: json.dumps()

json.dumps() ("dump string") goes the other way. Without options you get one compact line, ideal for sending over a network. Add indent=2 for readable, multi-line output, and sort_keys=True to order the keys alphabetically.

Only some Python types have a JSON equivalent: dicts with string keys, lists, tuples (they become arrays), strings, numbers, True, False and None. Anything else — a set, a date, your own object — raises TypeError: Object of type ... is not JSON serializable, so convert it first.

Reading nested data

Real JSON is usually nested: a dict that contains lists of dicts. Work from the outside in, one key or index at a time. Use .get() for keys that might be missing, so your program doesn't crash on incomplete data.

Python
import json

order = json.loads('''
{"id": 1042,
 "customer": {"name": "Ben", "city": "Pune"},
 "items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}]}
''')
print(order["customer"]["city"])
print(order["items"][0]["sku"])
print(sum(item["qty"] for item in order["items"]))
print(order.get("discount", 0))

JSON files: json.dump() and json.load()

The versions without the "s" work with files instead of strings: json.dump(data, f) writes to an open file, and json.load(f) reads one back. Together they are the easiest way to save a program's data and load it next time. (On this site, files live in your browser's temporary in-memory file system.)

JSON is stricter than Python

JSON requires double quotes around strings and keys, does not allow a trailing comma after the last item, and has no comments. When json.loads() meets any of these, it raises json.JSONDecodeError with the line and column where it gave up — a good place to start looking.

Quick reference: Python JSON

4Python JSON: syntax

import json

data = json.loads(text)                # JSON string -> dict / list
text = json.dumps(data)                # dict / list -> compact JSON string
text = json.dumps(data, indent=2)      # pretty, multi-line JSON

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)       # write to a file
with open("data.json") as f:
    data = json.load(f)                # read from a file

5Python JSON: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
import json

response_text = '''
{"user": "asha_k", "verified": true, "nickname": null,
 "books": [
   {"title": "Dune", "pages": 412},
   {"title": "Emma", "pages": 474}
 ]}
'''

data = json.loads(response_text)
print(data["user"], data["verified"], data["nickname"])

total = sum(book["pages"] for book in data["books"])
print("Books:", len(data["books"]), "| Pages:", total)

data["books"].append({"title": "Holes", "pages": 233})
print(json.dumps(data["books"][-1]))
print(json.dumps({"user": data["user"], "count": len(data["books"])}, indent=2))
Expected outputasha_k True None
Books: 2 | Pages: 886
{"title": "Holes", "pages": 233}
{
  "user": "asha_k",
  "count": 3
}

7Python JSON: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1json is part of the standard library, so a plain import is all you need.
  2. Line 3-9The JSON arrives as one string — exactly what you would get from a file or a web API. Note the JSON spellings true and null.
  3. Line 11json.loads() parses the text into a Python dict.
  4. Line 12The values are now Python values: true became True and null became None.
  5. Line 14data["books"] is a list of dicts. The generator expression adds up the "pages" value of each book: 412 + 474.
  6. Line 15len() counts the books and the total is printed.
  7. Line 17Parsed JSON is ordinary Python data, so you can change it — here a third book is appended to the list.
  8. Line 18json.dumps() turns the new book back into compact JSON text. Notice the double quotes: this is JSON, not a Python dict.
  9. Line 19indent=2 produces readable, multi-line JSON — handy for saving files people may open.

8Python JSON: common mistakes

Writing JSON with single quotes

✗ Wrong

import json
user = json.loads("{'name': 'Asha'}")
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

✓ Right

import json
user = json.loads('{"name": "Asha"}')
print(user["name"])

JSON only accepts double quotes. Wrap the JSON text in single quotes on the Python side so you can use double quotes inside it.

Using the JSON string as if it were a dict

✗ Wrong

import json
text = '{"city": "Pune", "temp": 31}'
print(text["city"])
TypeError: string indices must be integers, not 'str'

✓ Right

import json
text = '{"city": "Pune", "temp": 31}'
weather = json.loads(text)
print(weather["city"])

JSON text is just a string until you parse it. Call json.loads() first, then use keys on the resulting dict.

Mixing up load() and loads()

✗ Wrong

import json
text = '{"theme": "dark"}'
settings = json.load(text)
AttributeError: 'str' object has no attribute 'read'

✓ Right

import json
text = '{"theme": "dark"}'
settings = json.loads(text)
print(settings["theme"])

json.load() expects an open file. For a string, use json.loads() — the "s" stands for string.

9Python JSON: exercises

Write your answer, then press Check. The checks run in your browser.

1. Describe a product from JSON

Write code Easy

Write a function describe(json_text) that parses a JSON product such as {"name": "Lamp", "price": 24.5, "in_stock": true} and returns a string like "Lamp costs $24.50". If in_stock is false, add " (sold out)" to the end.

Your code
import json

def describe(json_text):
    # parse json_text with json.loads, then build and return the message
    pass

print(describe('{"name": "Lamp", "price": 24.5, "in_stock": true}'))
print(describe('{"name": "Desk", "price": 120, "in_stock": false}'))

2. Predict the conversions

Predict the output Medium

Read the code and type exactly what it prints. Watch the spelling of null/None and false/False on each line.

Read this code
import json

data = json.loads('{"a": [1, 2, {"b": null}], "c": false}')
print(data["a"][2])
print(len(data), data["c"])
print(json.dumps(data))

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

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

json.loads() parses a string that contains JSON. json.load() reads JSON from an open file object. The same pattern applies to json.dumps() (returns a string) and json.dump() (writes to a file).

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

JSON only has objects, arrays, strings, numbers, true/false and null. Convert other values before calling dumps(): a set to a sorted list, a date to a string with isoformat(), and your own objects to a dict of their attributes.

Is JSON the same as a Python dictionary?

No. JSON is text with its own rules (double quotes only, true/false/null, no trailing commas). A dict is a Python object in memory. json.loads() and json.dumps() convert between the two.

Further reading

10Next lesson

Up nextPython CSV FilesA CSV file stores a table as plain text — one row per line, values separated by commas — and Python's csv module reads …

Related:
Python DictionariesPython CSV FilesPython requests: Call Web APIsPython API Example: Build an API Client

← Python Dataclasses · All Practical Python lessons · Practise in the IDE