Reading history

Python JSON: dumps, loads, dump and load with Examples

5 min read 1 views

Learn the Python json module: converting dicts to JSON and back, type mapping, pretty printing, API data, files, dates and custom types, and JSONDecodeError.

JSON (JavaScript Object Notation) is the text format that web APIs, configuration files and many databases use to exchange data. It looks almost exactly like Python dictionaries and lists, and Python’s built-in json module converts between the two in one call. The File Handling lesson showed saving and loading a list; this lesson goes further, covering conversion rules, pretty printing, API-style data, custom types and error handling.

In this lesson you will learn

  • json.dumps and json.loads for strings
  • json.dump and json.load for files
  • How Python and JSON types map to each other
  • Pretty printing with indent and sort_keys
  • Handling dates and other unsupported types, and invalid JSON

Converting Between Python and JSON

import json

student = {
    "name": "Nusrat",
    "cgpa": 3.82,
    "graduated": False,
    "courses": ["Data Structures", "Databases"],
    "advisor": None,
}

text = json.dumps(student)                 # Python object -> JSON string
print(text)
print(type(text).__name__)

pretty = json.dumps(student, indent=2, sort_keys=True)
print(pretty)

back = json.loads(text)                    # JSON string -> Python object
print(back["courses"][1], back["graduated"], back["advisor"])
print(back == student)

Output

{"name": "Nusrat", "cgpa": 3.82, "graduated": false, "courses": ["Data Structures", "Databases"], "advisor": null}
str
{
  "advisor": null,
  "cgpa": 3.82,
  "courses": [
    "Data Structures",
    "Databases"
  ],
  "graduated": false,
  "name": "Nusrat"
}
Databases False None
True
  • json.dumps() (“dump string”) turns a Python object into a JSON string. Notice the changes: False becomes false, None becomes null, and all strings use double quotes.
  • indent=2 spreads the output over several lines for people to read; sort_keys=True sorts the keys alphabetically.
  • json.loads() (“load string”) parses JSON text back into Python dictionaries and lists, and the round trip gives an equal object.
PythonJSON
dictobject {}
list, tuplearray []
strstring (double quotes)
int, floatnumber
True / Falsetrue / false
Nonenull

API Data, Files, Custom Types and Errors

import json
from datetime import date

# A response like one from a web API
response = '''
{"status": "ok",
 "results": [
   {"id": 1, "city": "Dhaka", "temp": 31.5},
   {"id": 2, "city": "Sylhet", "temp": 27.0},
   {"id": 3, "city": "Khulna", "temp": 33.2}
 ]}
'''
data = json.loads(response)
hot = [r["city"] for r in data["results"] if r["temp"] > 30]
print("Hot cities:", hot)
print("Missing key with .get():", data.get("page", 1))

# Tuples become lists; keys are always strings
print(json.loads(json.dumps({1: (2, 3)})))

# Types JSON does not know need help
event = {"title": "Exam", "on": date(2026, 12, 20)}
try:
    json.dumps(event)
except TypeError as e:
    print("TypeError:", e)
print(json.dumps(event, default=str))

with open("settings.json", "w", encoding="utf-8") as f:
    json.dump({"theme": "dark", "lang": "bn"}, f, ensure_ascii=False)
with open("settings.json", encoding="utf-8") as f:
    print(json.load(f))

try:
    json.loads("{'name': 'x'}")            # single quotes are not valid JSON
except json.JSONDecodeError as e:
    print("JSONDecodeError:", e.msg)

import os; os.remove("settings.json")

Output

Hot cities: ['Dhaka', 'Khulna']
Missing key with .get(): 1
{'1': [2, 3]}
TypeError: Object of type date is not JSON serializable
{"title": "Exam", "on": "2026-12-20"}
{'theme': 'dark', 'lang': 'bn'}
JSONDecodeError: Expecting property name enclosed in double quotes
  • API responses are usually a dictionary containing lists of dictionaries. After json.loads, ordinary indexing and comprehensions pull out what you need. Use .get() for keys that may be missing.
  • The conversion is not perfectly reversible: tuples come back as lists, and dictionary keys always come back as strings (1 became '1').
  • Objects JSON has no type for, such as date, datetime, sets or your own classes, raise TypeError. The default argument supplies a converter; default=str is a quick fix, and a custom function gives full control.
  • json.dump(obj, file) and json.load(file) work directly with open files. ensure_ascii=False keeps non-English text, such as Bangla, readable in the file instead of escaping it as \u codes.
  • Invalid JSON raises json.JSONDecodeError. Single quotes, trailing commas and comments are all invalid in JSON, even though they are fine in Python.

Common Mistakes

  1. Confusing dump and dumps: the version ending in s works with strings, the other with files.
  2. Building JSON by string concatenation, which breaks on quotes and special characters; always use json.dumps.
  3. Expecting integer keys to survive a round trip.
  4. Calling str(dict) and treating the result as JSON; it uses single quotes and True/None, which JSON rejects.

Practice Exercises

Exercise 1. Parse '{"items": [{"name": "pen", "price": 20}, {"name": "bag", "price": 950}]}' and print the total price.

Show answer
import json
data = json.loads('{"items": [{"name": "pen", "price": 20}, {"name": "bag", "price": 950}]}')
print(sum(item["price"] for item in data["items"]))   # 970

Exercise 2. Write a default function that converts sets to sorted lists, so json.dumps({"tags": {"b", "a"}}, default=...) works.

Show answer
def encode(obj):
    if isinstance(obj, set):
        return sorted(obj)
    raise TypeError(f"Cannot encode {type(obj).__name__}")

print(json.dumps({"tags": {"b", "a"}}, default=encode))   # {"tags": ["a", "b"]}

Frequently Asked Questions

How do I get JSON from a web API?

Fetch the response with a library such as requests and call response.json(), which runs json.loads on the body for you. With only the standard library, use urllib.request and then json.loads.

What is the difference between JSON and a Python dictionary?

A dictionary is a Python object in memory. JSON is text that follows strict rules so any language can read it. The json module translates between the two.

Summary

  • dumps/loads convert to and from strings; dump/load use files.
  • JSON uses double quotes, true, false and null.
  • Use indent for readable output and ensure_ascii=False for non-English text.
  • Handle unsupported types with default and bad input with JSONDecodeError.

Next: Python collections Module.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *