Python Tutorial menu

Python JSON

JSON is the most common text format for sending and saving data, and Python's json module converts it to and from Python objects.

What is JSON?

JSON (JavaScript Object Notation) is plain text that stores data in a structured way. Web APIs, mobile apps and config files use it everywhere. It looks very much like a Python dictionary:

Example

json
{
  "name": "Ayesha Khan",
  "age": 21,
  "enrolled": true,
  "courses": ["Python", "Web Development"],
  "guardian": null
}

The rules are strict: keys must be in double quotes, and there are no comments and no trailing commas.

JSON and Python Types

JSONPython
object {}dict
array []list
string "text"str
number 21 or 3.5int or float
true / falseTrue / False
nullNone

From JSON Text to Python: loads()

json.loads() ("load string") reads JSON text and gives back Python objects.

Example

python
import json

text = '{"name": "Ayesha", "age": 21, "enrolled": true, "courses": ["Python", "SEO"], "guardian": null}'
student = json.loads(text)

print(type(student))
print(student["name"])
print(student["courses"][0])
print(student["enrolled"], student["guardian"])
Output
<class 'dict'>
Ayesha
Python
True None

Notice that true became True and null became None.

From Python to JSON Text: dumps()

json.dumps() ("dump string") turns Python objects into JSON text.

Example

python
import json

order = {"id": 501, "items": ("tea", "samosa"), "paid": False, "tip": None}
text = json.dumps(order)
print(text)
print(type(text))

print(json.dumps(order, indent=2))
Output
{"id": 501, "items": ["tea", "samosa"], "paid": false, "tip": null}
<class 'str'>
{
  "id": 501,
  "items": [
    "tea",
    "samosa"
  ],
  "paid": false,
  "tip": null
}

The tuple became a JSON array. indent=2 makes the text easy for people to read.

Useful dumps() Options

OptionWhat it does
indent=2Pretty prints with 2 spaces
sort_keys=TruePuts the keys in A to Z order
ensure_ascii=FalseKeeps Urdu and other non-English letters readable
separators=(",", ":")Removes spaces for the smallest output
default=strConverts unknown types (like dates) to text

Example

python
import json
from datetime import date

data = {"city": "کراچی", "joined": date(2026, 10, 15), "batch": 7}

print(json.dumps(data, default=str))
print(json.dumps(data, default=str, ensure_ascii=False, sort_keys=True))
Output
{"city": "\u06a9\u0631\u0627\u0686\u06cc", "joined": "2026-10-15", "batch": 7}
{"batch": 7, "city": "کراچی", "joined": "2026-10-15"}

Without default=str, a date would raise TypeError: Object of type date is not JSON serializable.

Saving and Loading a File

With files, use json.dump() and json.load(). They have no "s" at the end because they work with a file, not a string.

Example

python
import json

contacts = [
    {"name": "Ali", "phone": "0300-1112233"},
    {"name": "Sara", "phone": "0321-4445566"},
]

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

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

loaded.append({"name": "Omar", "phone": "0333-7778899"})
for c in loaded:
    print(c["name"], c["phone"])
Output
Ali 0300-1112233
Sara 0321-4445566
Omar 0333-7778899

Easy way to remember: dumps and loads work with a string. dump and load work with a file.

Handling Bad JSON

If the text is not valid JSON, loads() raises json.JSONDecodeError. Catch it so your program does not crash.

Example

python
import json

samples = ['{"price": 250}', "{'price': 250}", '{"price": 250,}']
for s in samples:
    try:
        print("OK:", json.loads(s))
    except json.JSONDecodeError as err:
        print("Bad JSON:", err.msg)
Output
OK: {'price': 250}
Bad JSON: Expecting property name enclosed in double quotes
Bad JSON: Illegal trailing comma before end of object

Single quotes and trailing commas are fine in Python, but not in JSON.

Reading Nested Data

Real JSON from an API is often nested. Use normal indexing, and .get() for keys that might be missing.

Example

python
import json

reply = '''
{
  "shop": "Saddar Electronics",
  "products": [
    {"name": "Power bank", "price": 3200, "stock": 14},
    {"name": "Earbuds", "price": 2100, "stock": 0},
    {"name": "Charger", "price": 950}
  ]
}
'''
data = json.loads(reply)
print(data["shop"])
for p in data["products"]:
    stock = p.get("stock", "unknown")
    print(f"- {p['name']}: Rs {p['price']} (stock: {stock})")
Output
Saddar Electronics
- Power bank: Rs 3200 (stock: 14)
- Earbuds: Rs 2100 (stock: 0)
- Charger: Rs 950 (stock: unknown)

You will use exactly this skill in the Working With APIs lesson.

Exercise

Exercise

Which function turns a JSON string into a Python dictionary?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp