Skip to content
Laviyx Learn

Try

Python course menu

Python JSON: Read, Write and Parse JSON Data

Learn to work with JSON in Python: convert dictionaries to JSON with dumps, parse JSON strings with loads, read and write JSON files with dump and load, navigate nested API data, and handle common JSON errors.

Intermediate6 min readUpdated
On this page

JSON (JavaScript Object Notation) is the most common format for exchanging data between programs: web APIs, configuration files, and many databases use it. JSON looks almost exactly like Python dictionaries and lists, and the built-in json module converts between the two.

JSON and Python side by side#

JSONPython
object {"a": 1}dict
array [1, 2]list
string "text" (double quotes only)str
number 42, 3.5int, float
true / falseTrue / False
nullNone

Python to JSON text: dumps#

json.dumps() ("dump string") turns Python data into a JSON string:

Python
import json

student = {"name": "Asha", "age": 21, "skills": ["python", "sql"],
           "active": True, "mentor": None}
text = json.dumps(student)
print(text)
print(type(text).__name__)
Output
{"name": "Asha", "age": 21, "skills": ["python", "sql"], "active": true, "mentor": null}
str

Notice True became true and None became null. Add indent for readable output:

Python
print(json.dumps({"name": "Asha", "age": 21, "skills": ["python", "sql"]}, indent=2))
Output
{
  "name": "Asha",
  "age": 21,
  "skills": [
    "python",
    "sql"
  ]
}

JSON text to Python: loads#

json.loads() ("load string") parses JSON text into Python objects:

Python
text = '{"name": "Ravi", "age": 25, "active": false, "scores": [85, 90]}'
data = json.loads(text)

print(data["name"], data["active"], sum(data["scores"]))
print(type(data).__name__)
Output
Ravi False 175
dict

After parsing, it is an ordinary dictionary: index it, loop over it, change it.

Reading and writing JSON files#

json.dump() and json.load() (no "s") work with files directly:

Python
settings = {"theme": "dark", "font_size": 14, "languages": ["en", "hi"]}

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

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

print(loaded == settings, loaded["languages"])
Output
True ['en', 'hi']

API responses are usually nested. Work from the outside in:

Python
response = '''{
  "user": {"id": 7, "name": "Meera"},
  "orders": [
    {"id": 101, "total": 250},
    {"id": 102, "total": 120}
  ]
}'''

data = json.loads(response)
print(data["user"]["name"])
print([o["id"] for o in data["orders"]])
print(sum(o["total"] for o in data["orders"]))
Output
Meera
[101, 102]
370

Non-English text#

By default, non-ASCII characters are escaped. Pass ensure_ascii=False to keep them readable:

Python
print(json.dumps({"city": "पुणे"}), json.dumps({"city": "पुणे"}, ensure_ascii=False))
Output
{"city": "\u092a\u0941\u0923\u0947"} {"city": "पुणे"}

Both are valid JSON and load back to the same string.

Common errors#

Invalid JSON. JSON is stricter than Python: keys and strings need double quotes, and trailing commas are not allowed.

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

Catch json.JSONDecodeError when parsing data you do not control. The JSON Formatter tool can show you exactly where a JSON document is broken.

Types JSON does not support. Dates, sets and custom objects cannot be converted automatically:

Python
from datetime import date
json.dumps({"day": date(2026, 10, 23)})
Output
TypeError: Object of type date is not JSON serializable

The quickest fix is default=str, which converts unknown objects to strings:

Python
print(json.dumps({"day": date(2026, 10, 23)}, default=str))
Output
{"day": "2026-10-23"}

Common mistakes#

Practice#

Practice exercise

Parse the response JSON from the "Navigating nested JSON" section and print a line for each order like Order 101: ₹250, followed by Meera spent ₹370.

Show hint

Loop over data["orders"]; use data["user"]["name"] and sum(...) for the last line.

Show solution
Python
import json

data = json.loads(response)
for order in data["orders"]:
    print(f"Order {order['id']}: ₹{order['total']}")

total = sum(o["total"] for o in data["orders"])
print(f"{data['user']['name']} spent ₹{total}")
Output
Order 101: ₹250
Order 102: ₹120
Meera spent ₹370

Inside an f-string that uses double quotes, use single quotes for the dictionary keys.

Key takeaway#

Finished this lesson?