Working with JSON
Published by Brayan K
JSON is the universal language of data on the internet. Every web API you'll ever call, most config files, and countless data feeds use it. Python's json module converts between JSON text and native Python objects in one line each direction.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
From JSON text to lists and dictionaries
JSON is common across web APIs. Some APIs return XML, text, binary data or other formats instead. Check the API's documentation and response format before parsing it as JSON.
JSON is text in a fixed format. json.loads() reads it into Python's own values, mostly the lists and dictionaries that Dictionaries ended with, and the rest is ordinary Python:
import json
response = '''
{
"status": "ok",
"results": [
{"id": 1, "title": "Intro to Python", "published": true},
{"id": 2, "title": "Advanced JSON", "published": false}
]
}
'''
data = json.loads(response)
print("Status:", data["status"])
print("Number of results:", len(data["results"]))
for course in data["results"]:
if course["published"]:
state = "live"
else:
state = "draft"
print(f'- #{course["id"]} {course["title"]} ({state})')
# ✅ Expected output:
# Status: ok
# Number of results: 2
# - #1 Intro to Python (live)
# - #2 Advanced JSON (draft)JSON looks like Python's dictionaries and lists, with a few differences:
| JSON | Python |
|---|---|
| { } object | dict, whose keys are always text |
| [ ] array | list |
| "text", double quotes only | str |
| true false | True False |
| null | None |
| 42 3.14 | int float |
json.dumps() goes the other way, from Python values to JSON text:
import json
user = {"name": "Ada", "admin": True, "manager": None}
print(user)
print(json.dumps(user))
# ✅ Expected output:
# {'name': 'Ada', 'admin': True, 'manager': None}
# {"name": "Ada", "admin": true, "manager": null}A printed dictionary is not JSON
The two lines above look alike, which tempts people to save a dictionary with str() or print(). That text uses single quotes and True, so it isn't JSON, and reading it back fails:
import json
user = {"name": "Ada", "admin": True}
text = str(user)
print(text)
json.loads(text)
# ✅ Expected output:
# {'name': 'Ada', 'admin': True}
# ✅ Expected error:
# json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)The same goes for JSON typed by hand with Python's spellings. Lower-case true reads fine; True doesn't:
import json
print(json.loads('{"name": "Ada", "admin": true, "manager": null}'))
print(json.loads('{"name": "Ada", "admin": True}'))
# ✅ Expected output:
# {'name': 'Ada', 'admin': True, 'manager': None}
# ✅ Expected error:
# json.decoder.JSONDecodeError: Expecting value: line 1 column 26 (char 25)The error gives the line, the column and the character position where reading stopped, which is where to look. Empty text, such as an empty file or an empty reply, stops at the very first character with "Expecting value". JSON also refuses comments and a comma after the last item, both of which hand-written files often have.
loads and dumps take text; load and dump take a file
The s in loads and dumps stands for string: they read and write text. Give loads() something that is already a dictionary and it refuses:
import json
json.loads({"user": "ada"})
# ✅ Expected error:
# TypeError: the JSON object must be str, bytes or bytearray, not dictWithout the s, dump() and load() write to and read from an open file. The with open(...) as f: lines open a file for the indented block and close it afterwards; File Handling covers them:
import json
scores = [{"name": "ada", "score": 40}]
with open("scores.json", "w") as f:
json.dump(scores, f)
with open("scores.json") as f:
print(json.load(f))
# ✅ Expected output:
# [{'name': 'ada', 'score': 40}]Give dump() a file name instead of an open file and it fails when it tries to write:
import json
scores = [{"name": "ada", "score": 40}]
json.dump(scores, "scores.json")
# ✅ Expected error:
# AttributeError: 'str' object has no attribute 'write'A round trip changes some types
JSON has fewer types than Python, so writing some values out and reading them back doesn't give the same values. A tuple comes back as a list, and number keys come back as text:
import json
back = json.loads(json.dumps((3, 4)))
print(back, back == (3, 4))
medals = {1: "gold", 2: "silver"}
back = json.loads(json.dumps(medals))
print(back)
print(back["1"])
print(back[1])
# ✅ Expected output:
# [3, 4] False
# {'1': 'gold', '2': 'silver'}
# gold
# ✅ Expected error:
# KeyError: 1Some values have no JSON form at all, such as a set or a date:
import json
print(json.dumps({"python", "web"}))
# ✅ Expected error:
# TypeError: Object of type set is not JSON serializableWhen the set sits inside a dictionary or a list, as in {"tags": {"python"}}, Python 3.14 adds a line under that error saying where it was: when serializing dict item 'tags'.
Convert them yourself before writing: a sorted list for a set, and the standard text for a date, from Dates & Times (datetime):
import json
from datetime import date
tags = {"web", "python", "api"}
record = {"tags": sorted(tags), "due": date(2024, 3, 1).isoformat()}
print(json.dumps(record))
# ✅ Expected output:
# {"tags": ["api", "python", "web"], "due": "2024-03-01"}dumps() also takes default=str, which turns anything it can't write into Python's text for it. That stops the error, but a set then arrives as a piece of text such as "{'b'}", which the program reading it can't use as a list, so converting deliberately is safer.
A failed dump() can leave half a file
dump() writes as it goes, and opening the file with "w" has already emptied it. So when a value it can't write turns up halfway through, the error stops the program with the start of the JSON already in the file:
import json
from datetime import date
order = {"id": 7, "due": date(2024, 3, 1)}
with open("order.json", "w") as f:
json.dump(order, f)It stops with TypeError: Object of type date is not JSON serializable, and on Python 3.14 a line under it says where: when serializing dict item 'due'. order.json now holds {"id": 7, "due": and nothing more, and whatever it held before is gone. Build the text with dumps() first, so an error stops the program before the file is touched:
import json
from datetime import date
order = {"id": 7, "due": date(2024, 3, 1).isoformat()}
text = json.dumps(order)
with open("order.json", "w") as f:
f.write(text)
with open("order.json") as f:
print(f.read())
# ✅ Expected output:
# {"id": 7, "due": "2024-03-01"}Nested data, and null
Real JSON nests: objects inside objects, lists inside them. Read a long chain of brackets from the left, one step at a time:
import json
user = json.loads('{"name": "Ada", "address": {"city": "London", "zip": null}, "roles": ["admin", "editor"]}')
print(user["address"]["city"])
print(user["roles"][-1])
print(user["address"]["zip"])
# ✅ Expected output:
# London
# editor
# NoneA null can stand where an object usually is, and then the next step of the chain has nothing to look in:
import json
user = json.loads('{"name": "Ada", "address": null}')
print(user["address"]["city"])
# ✅ Expected error:
# TypeError: 'NoneType' object is not subscriptableor gives its right side when the left is None, as Operators and Expressions showed, and .get() gives a default for a missing key:
import json
user = json.loads('{"name": "Ada", "address": null}')
address = user["address"] or {}
print(address.get("city", "unknown"))
# ✅ Expected output:
# unknownReadable JSON: indent and sort_keys
dumps() writes everything on one line. indent=2 spreads it over lines, two spaces deeper at each level, and sort_keys=True puts the keys in order, capitals first:
import json
report = {
"generated": "2024-01-15",
"totals": {"users": 1240, "active": 892},
"top_pages": ["/home", "/pricing", "/docs"],
"healthy": True,
}
pretty = json.dumps(report, indent=2, sort_keys=True)
print(pretty)
again = json.loads(pretty)
print()
print("Round trip OK?", again == report)
# ✅ Expected output:
# {
# "generated": "2024-01-15",
# "healthy": true,
# "top_pages": [
# "/home",
# "/pricing",
# "/docs"
# ],
# "totals": {
# "active": 892,
# "users": 1240
# }
# }
#
# Round trip OK? TrueThe spaces and line breaks don't change what the JSON means, so the text reads back as an equal dictionary. Use the readable form for files people open, such as settings.
Practice: parse, change, write back
Fill the three blanks with the values in the hint lines, in order: read the text into a dictionary, then write the changed dictionary back as text with its keys in order.
import json
payload = '{"user": "ada", "score": 40, "badges": ["starter"]}'
data = json.___(payload)
data["score"] += 10
print(json.___(data, sort_keys=___))
# 👉 replace ___ with loads
# 👉 replace ___ with dumps
# 👉 replace ___ with True
# ✅ Expected output:
# {"badges": ["starter"], "score": 50, "user": "ada"}On your own: a leaderboard
A game sends its scores as JSON text: . Read it, add alan with 52 points, sort the players by score from the highest, print a numbered ranking such as 1. grace - 65, and finally print the leader as JSON text. Then compare with this solution:
import json
raw = '[{"name": "ada", "score": 40}, {"name": "grace", "score": 65}]'
scores = json.loads(raw)
scores.append({"name": "alan", "score": 52})
scores.sort(key=lambda s: s["score"], reverse=True)
for rank, s in enumerate(scores, start=1):
print(f"{rank}. {s['name']} - {s['score']}")
print(json.dumps(scores[0]))
# ✅ Expected output:
# 1. grace - 65
# 2. alan - 52
# 3. ada - 40
# {"name": "grace", "score": 65}Once parsed, the scores are an ordinary list of dictionaries, so the sorting is Lambda Functions' key and the numbering is enumerate & zip's start=1. Only the first and last lines touch JSON.
Practice quiz
What does print(json.dumps({"ok": True, "n": None})) print?
- {'ok': True, 'n': None}
- {"ok": true, "n": null}
- {"ok": True, "n": None}
- An error
Answer: {"ok": true, "n": null}. JSON writes true, false and null in lower case, and only double quotes.
What does json.loads("{'a': 1}") do?
- It gives {'a': 1}
- It gives the text {"a": 1}
- It stops with a JSONDecodeError: Expecting property name enclosed in double quotes
- It gives None
Answer: It stops with a JSONDecodeError: Expecting property name enclosed in double quotes. JSON allows only double quotes, so text in Python's dictionary style isn't JSON.
What does print(json.loads(json.dumps({1: "gold"}))) print?
- {'1': 'gold'}
- {1: 'gold'}
- {"1": "gold"}
- An error
Answer: {'1': 'gold'}. JSON keys are always text, so the number 1 comes back as the string '1'.
What does print(json.loads(json.dumps((3, 4)))) print?
- (3, 4)
- '(3, 4)'
- An error
- [3, 4]
Answer: [3, 4]. JSON has arrays but no tuples, so a tuple comes back as a list.
What does json.dumps({"tags": {"a"}}) do?
- It gives {"tags": ["a"]}
- It gives {"tags": "a"}
- It gives {"tags": {"a"}}
- It stops with TypeError: Object of type set is not JSON serializable
Answer: It stops with TypeError: Object of type set is not JSON serializable. JSON has no sets. Convert one first, for example with sorted().
What does json.dump(data, "out.json") do?
- It writes out.json
- It stops with AttributeError: 'str' object has no attribute 'write'
- It returns the JSON text
- It stops with FileNotFoundError
Answer: It stops with AttributeError: 'str' object has no attribute 'write'. dump() without the s writes to an open file, not to a file name.
What does print(type(json.loads("[1, 2]")).__name__) print?
- list
- str
- tuple
- dict
Answer: list. A JSON array becomes a Python list.
What does json.loads("") do?
- It gives {}
- It gives None
- It stops with a JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- It gives ''
Answer: It stops with a JSONDecodeError: Expecting value: line 1 column 1 (char 0). Empty text isn't JSON. This is the error an empty response or an empty file gives.
Continue this course
- Previous: Dates & Times (datetime)
- Next: HTTP Requests & APIs — Call REST APIs and handle responses with the requests library
- Quick reference: Python cheat sheet › Standard Library
Frequently asked questions
Should I use JSON or pickle to save Python data?
JSON for anything another program or person might read: it's plain text, and every language can parse it, but it holds only dicts, lists, text, numbers, True, False and None. pickle stores almost any Python object, but only Python can read it, and loading a pickle from an untrusted source can run code. Serialization with pickle covers it.
How do I get JSON from a web API?
The requests library fetches the page, and response.json() runs json.loads() on its text for you, handing back the same lists and dictionaries as in this lesson. HTTP Requests & APIs shows it.
How do I stop the program from crashing on bad JSON?
Catch the error. json.JSONDecodeError is a kind of ValueError, so try: data = json.loads(text) with except json.JSONDecodeError: lets the program carry on, for example by reporting which input was bad. Exception Handling covers try and except.