You call a weather API and get back a block of text full of curly braces, square brackets and quotes. You open a project's package.json or a VS Code settings.json and see the same thing. A teammate asks you to "send the data as JSON". JSON is everywhere in programming, and the good news is that it takes about ten minutes to learn. This lesson is JSON for beginners: what it is, its rules, and how to read and write it in Python.
JSON (JavaScript Object Notation, pronounced "jay-son") is a text format for structured data. It started in JavaScript, but every major language can read and write it, which is why APIs, config files and databases use it to pass data between programs written in different languages.
What you need first: what is an API? helps for context. Knowing Python dictionaries and lists makes the Python part easier.
Key terms
- JSON: a text format for data, made of objects, arrays and simple values.
- Object: a set of
"key": valuepairs inside{ }. Like a Python dictionary. - Array: an ordered list of values inside
[ ]. Like a Python list. - Key: the name of a value in an object; always a string in double quotes.
- Serialise (encode): turn data in your program into JSON text.
- Parse (deserialise, decode): turn JSON text into data your program can use.
What JSON looks like
A student record in JSON:
{
"name": "Ahana Khan",
"roll_no": 42,
"cgpa": 8.7,
"hosteller": true,
"mentor": null,
"subjects": ["Maths", "Python", "DBMS"],
"address": {
"city": "Lucknow",
"pincode": "226001"
}
}
It reads almost like English: the name is "Ahana Khan", the roll number is 42, the subjects are a list, and the address is another object inside the first one.
The rules
JSON has only six kinds of value:
| Type | Example | Python equivalent |
|---|---|---|
| String | "Ahana" | str |
| Number | 42, 8.7, -3, 1.5e3 | int or float |
| Boolean | true, false | True, False |
| Null | null | None |
| Array | ["Maths", "Python"] | list |
| Object | {"city": "Lucknow"} | dict |
And a few strict rules:
- Strings and keys use double quotes:
"name", never'name'. - Keys must be strings:
{"42": "Ahana"}is fine;{42: "Ahana"}isn't. - No trailing commas:
[1, 2, 3,]is invalid. - No comments:
//and#aren't allowed. true,falseandnullare lower-case.- No other types: no dates, no sets, no
NaN. Dates are usually written as strings like"2026-12-04".
Objects and arrays can be nested inside each other to any depth, which is how JSON represents complex data like an order with many items, each with its own details.
Notice "pincode": "226001" is a string, not a number. Codes like PIN codes, phone numbers and IDs with leading zeros should be strings, because they're labels, not quantities you'd do maths with.
JSON in Python: the json module
Python's built-in json module does the converting. There are four functions to know:
| Function | Converts | From / to |
|---|---|---|
json.loads(text) | JSON text → Python | a string |
json.dumps(data) | Python → JSON text | a string |
json.load(file) | JSON file → Python | a file |
json.dump(data, file) | Python → JSON file | a file |
The s stands for "string". Without s, they work with files.
Parsing JSON text
import json
text = '{"name": "Ahana Khan", "roll_no": 42, "hosteller": true, "mentor": null, "subjects": ["Maths", "Python"]}'
student = json.loads(text)
print(type(student))
print(student["name"])
print(student["subjects"][1])
print(student["hosteller"], student["mentor"])
<class 'dict'>
Ahana Khan
Python
True None
JSON true became Python True, and null became None. After parsing, it's an ordinary dictionary.
Creating JSON text
import json
order = {
"order_id": 5012,
"items": [{"name": "Masala Dosa", "qty": 2, "price": 90}],
"paid": False,
"coupon": None,
}
print(json.dumps(order))
print(json.dumps(order, indent=2))
{"order_id": 5012, "items": [{"name": "Masala Dosa", "qty": 2, "price": 90}], "paid": false, "coupon": null}
{
"order_id": 5012,
"items": [
{
"name": "Masala Dosa",
"qty": 2,
"price": 90
}
],
"paid": false,
"coupon": null
}
The first form is compact, for sending over a network. indent=2 makes it readable for people and config files.
Reading and writing JSON files
import json
settings = {"theme": "dark", "font_size": 14, "language": "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)
print(loaded["language"])
True
hi
Non-English text
By default, json.dumps turns non-ASCII characters into \u codes. Add ensure_ascii=False to keep them readable:
import json
city = {"city": "दिल्ली"}
print(json.dumps(city))
print(json.dumps(city, ensure_ascii=False))
{"city": "दिल्ली"}
{"city": "दिल्ली"}
Both are valid JSON and mean the same thing. When writing files with ensure_ascii=False, open them with encoding="utf-8".
Working with nested JSON
API responses are often deeply nested. Read them one level at a time:
import json
response = '''
{
"city": "Pune",
"forecast": [
{"day": "Mon", "max_c": 31, "rain": false},
{"day": "Tue", "max_c": 29, "rain": true},
{"day": "Wed", "max_c": 30, "rain": true}
]
}
'''
data = json.loads(response)
print(data["forecast"][0]["max_c"])
rainy = [d["day"] for d in data["forecast"] if d["rain"]]
print(rainy)
31
['Tue', 'Wed']
data["forecast"] is a list, [0] is its first dictionary, and ["max_c"] is a value inside it. When a key might be missing, use .get() to avoid a KeyError. Nested data and JSON in Python goes much further.
Common errors
Invalid JSON raises json.JSONDecodeError, which tells you the line and column of the problem:
import json
bad_examples = [
"{'name': 'Ahana'}", # single quotes
'{"marks": [90, 85,]}', # trailing comma
'{"active": True}', # Python's True, not JSON's true
]
for text in bad_examples:
try:
json.loads(text)
except json.JSONDecodeError as error:
print(type(error).__name__, "at column", error.colno)
JSONDecodeError at column 2
JSONDecodeError at column 18
JSONDecodeError at column 12
The most common causes:
- Single quotes instead of double quotes, often from printing a Python dictionary and pasting it as JSON. A printed dict is not JSON; use
json.dumps(). - Trailing commas after the last item.
- Python values like
True,FalseandNoneinstead oftrue,falseandnull. - Comments in the file.
- Data types JSON doesn't support:
json.dumps()fails withTypeError: Object of type datetime is not JSON serializable. Convert dates to strings first, for example with.isoformat().
Online JSON validators and VS Code both highlight the exact problem, which makes these quick to fix.
Where JSON is used
| Place | Example |
|---|---|
| Web APIs | Almost every REST API sends and receives JSON |
| Config files | package.json, VS Code settings.json, tsconfig.json |
| Notebooks | Jupyter .ipynb files are JSON inside |
| Databases | MongoDB stores JSON-like documents; PostgreSQL has a JSON column type |
| Logs | Many systems write one JSON object per log line, which is easy to search |
You'll also meet YAML for configuration (Docker Compose, GitHub Actions, Kubernetes). It holds the same kinds of data with less punctuation, using indentation instead of braces. See YAML for beginners.
Practice
- Find the three mistakes in this JSON:
{name: "Rohan", 'city': "Kochi", "marks": [72, 81,]}
Show the answer
name has no quotes (keys must be strings in double quotes), 'city' uses single quotes, and there's a trailing comma after 81. Fixed: {"name": "Rohan", "city": "Kochi", "marks": [72, 81]}.
- What Python type does each JSON value become:
"5",5,5.0,false,null,[5],{"n": 5}?
Show the answer
str, int, float, bool, NoneType (the value None), list and dict.
- Parse this JSON and print the total quantity:
{"items": [{"name": "pen", "qty": 3}, {"name": "notebook", "qty": 2}]}
Show the answer
import json
data = json.loads('{"items": [{"name": "pen", "qty": 3}, {"name": "notebook", "qty": 2}]}')
print(sum(item["qty"] for item in data["items"]))
5
- Write Python that saves a list of three city names to
cities.json, reads it back, and prints how many cities there are.
Show the answer
import json
cities = ["Mumbai", "Chennai", "Guwahati"]
with open("cities.json", "w", encoding="utf-8") as f:
json.dump(cities, f)
with open("cities.json", encoding="utf-8") as f:
print(len(json.load(f)))
3
- Why should a mobile number be stored as
"09876543210"(a string) and not09876543210(a number) in JSON?
Show the answer
JSON numbers can't have leading zeros, so 09876543210 is invalid JSON, and even without the zero, a number type invites mistakes like rounding or adding. A phone number is a label, not a quantity, so it belongs in a string.
Key takeaways
- JSON is a text format for data built from objects
{}, arrays[], strings, numbers,true/falseandnull. - Keys and strings use double quotes; no trailing commas, no comments.
- In Python,
json.loads/json.dumpswork with strings, andjson.load/json.dumpwith files. - JSON objects become dictionaries and arrays become lists; read nested data one level at a time.
- A printed Python dictionary isn't JSON; always produce JSON with
json.dumps().
Frequently asked questions
Is JSON a programming language?
No. It's a data format, like CSV. It holds data but can't run any logic.
What is the difference between JSON and a Python dictionary?
A dictionary is a live object in your Python program. JSON is text that follows strict rules, used to store or send data. They look similar, but JSON needs double quotes, uses true/false/null, and only allows string keys.
JSON or CSV: which should I use?
Use CSV for flat tables with the same columns in every row, like a marks sheet, especially if it will be opened in Excel. Use JSON for nested or varying data, like an order with a list of items, and for APIs.
What to learn next
- See where APIs and apps run in what is the cloud?
- Handle real-world nested data with nested data and JSON in Python.
- Learn the other common config format with YAML for beginners.