Python JSON
JSON
JSON (JavaScript Object Notation) is a lightweight, text-based format for storing and exchanging data. It is easy for humans to read and easy for programs to parse, which is why it has become the standard data format for web APIs, configuration files, and communication between applications.
Here is a small JSON document:
{
"product": "Laptop",
"price": 55000,
"in_stock": true,
"tags": ["electronics", "computer"]
}
If you have studied Python dictionaries, JSON will look familiar. JSON objects map almost directly to Python dictionaries, and JSON arrays map to Python lists.
JSON Syntax Rules
JSON looks like Python, but it has stricter rules:
| Rule | JSON | Python |
|---|---|---|
| Strings and keys | Double quotes only: "name" | Single or double quotes |
| Boolean values | true, false | True, False |
| Empty value | null | None |
| Object keys | Must be strings | Many types allowed |
| Trailing commas | Not allowed | Allowed |
These differences are why you should always use the json module rather than trying to treat JSON text as Python code.
The json Module
Python includes a built-in json module for converting between JSON text and Python objects.
import json
The two most important functions are:
| Function | Converts | Remember It As |
|---|---|---|
json.loads() | JSON string → Python object | "load string" |
json.dumps() | Python object → JSON string | "dump string" |
Converting JSON text into Python objects is called parsing or deserialization. Converting Python objects into JSON text is called serialization.
Parsing JSON: JSON → Python
Data received from an API or read from a file usually arrives as a JSON string. Use json.loads() to convert it into a Python object.
Example: Converting a JSON String to a Dictionary
import json
json_data = '{ "product": "Laptop", "price": 55000, "brand": "Dell" }'
python_obj = json.loads(json_data)
print(python_obj["price"])
print(type(python_obj))
Expected output:
55000
<class 'dict'>
What happens:
json_datais a plain string. You cannot accessjson_data["price"]on a string.json.loads()parses the text and builds a Python dictionary.- The dictionary's values can now be accessed by key.
Notice that the JSON string is wrapped in single quotes in Python, so the double quotes inside it do not end the string.
JSON Values Are Converted Automatically
import json
text = '{"a": [1, 2], "b": null, "c": true}'
print(json.loads(text))
Expected output:
{'a': [1, 2], 'b': None, 'c': True}
The JSON null becomes None, and true becomes True.
Invalid JSON Raises an Error
import json
json.loads("{'name': 'Asha'}")
Output:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
The text uses single quotes, which are not valid in JSON. When parsing data from an external source, handle this error with try/except json.JSONDecodeError.
Converting Python to JSON: Python → JSON
Use json.dumps() to convert a Python object into a JSON-formatted string, ready to be saved to a file or sent over a network.
Example: Converting a Dictionary to JSON
import json
product = {
"product": "Mobile",
"price": 18000,
"brand": "Samsung"
}
json_string = json.dumps(product)
print(json_string)
print(type(json_string))
Expected output:
{"product": "Mobile", "price": 18000, "brand": "Samsung"}
<class 'str'>
The result is a string, even though it looks like a dictionary. All keys and text values now use double quotes, following JSON rules.
Supported Python Data Types
These Python types can be converted to JSON:
dictlisttuplestrintfloatTrueFalseNone
Example: Converting Different Python Types
import json
print(json.dumps({"course": "Python", "level": "Beginner"}))
print(json.dumps(["HTML", "CSS", "JavaScript"]))
print(json.dumps(("Red", "Green", "Blue")))
print(json.dumps("Welcome"))
print(json.dumps(99))
print(json.dumps(45.6))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
Expected output:
{"course": "Python", "level": "Beginner"}
["HTML", "CSS", "JavaScript"]
["Red", "Green", "Blue"]
"Welcome"
99
45.6
true
false
null
Notice:
- The tuple became a JSON array (square brackets). JSON has no tuple type.
True,False, andNonebecametrue,false, andnull.- The string
"Welcome"is wrapped in quotes in the JSON output.
Python-to-JSON Type Conversion Table
| Python Type | JSON Type |
|---|---|
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
Note: The conversion is not perfectly reversible. A tuple becomes a JSON array, and when parsed back it becomes a list, not a tuple. Dictionary keys that are numbers become strings:
json.dumps({1: "a"})produces{"1": "a"}.
Unsupported Types
Some Python types — such as sets, datetime objects, and custom class instances — cannot be converted directly:
import json
json.dumps({"tags": {"python", "json"}})
Output:
TypeError: Object of type set is not JSON serializable
Convert such values to a supported type first — for example, list(my_set) or my_date.isoformat().
Converting Complex Python Objects
Dictionaries can contain nested lists, tuples, and other dictionaries, and json.dumps() converts the entire structure.
import json
data = {
"student": "Amit",
"age": 21,
"is_graduated": False,
"subjects": ("Maths", "Science", "English"),
"address": None,
"devices": [
{"type": "Laptop", "brand": "HP"},
{"type": "Phone", "brand": "OnePlus"}
]
}
print(json.dumps(data))
Expected output:
{"student": "Amit", "age": 21, "is_graduated": false, "subjects": ["Maths", "Science", "English"], "address": null, "devices": [{"type": "Laptop", "brand": "HP"}, {"type": "Phone", "brand": "OnePlus"}]}
The output is valid JSON, but it is all on one line and hard to read.
Formatting JSON Output
json.dumps() has parameters for making the output easier to read.
Indentation With indent
The indent parameter adds line breaks and indents nested levels by the given number of spaces.
print(json.dumps(data, indent=4))
Expected output:
{
"student": "Amit",
"age": 21,
"is_graduated": false,
"subjects": [
"Maths",
"Science",
"English"
],
"address": null,
"devices": [
{
"type": "Laptop",
"brand": "HP"
},
{
"type": "Phone",
"brand": "OnePlus"
}
]
}
Indented JSON is often called "pretty-printed" JSON. It is ideal for configuration files and debugging. For data sent over a network, the compact form is usually preferred because it is smaller.
Custom Separators
The separators parameter takes a tuple of two strings: the separator between items and the separator between each key and its value. The defaults are ", " and ": ".
user = {"name": "Asha", "role": "admin"}
print(json.dumps(user, separators=(" | ", " => ")))
Expected output:
{"name" => "Asha" | "role" => "admin"}
Note: Custom separators like these produce text that is no longer valid JSON, so other programs cannot parse it. The practical use of
separatorsis to make JSON smaller by removing spaces:separators=(",", ":")produces{"name":"Asha","role":"admin"}.
Sorting Keys With sort_keys
sort_keys=True arranges the keys in alphabetical order at every level.
print(json.dumps(data, indent=4, sort_keys=True))
Expected output:
{
"address": null,
"age": 21,
"devices": [
{
"brand": "HP",
"type": "Laptop"
},
{
"brand": "OnePlus",
"type": "Phone"
}
],
"is_graduated": false,
"student": "Amit",
"subjects": [
"Maths",
"Science",
"English"
]
}
Sorted keys make JSON files easier to scan and compare between versions. Notice that the list items keep their original order — only dictionary keys are sorted.
Non-English Text With ensure_ascii
By default, json.dumps() escapes non-ASCII characters (such as Tamil, Hindi, or accented letters) into \u codes. Use ensure_ascii=False to keep them readable:
import json
print(json.dumps({"city": "சென்னை"}))
print(json.dumps({"city": "சென்னை"}, ensure_ascii=False))
Expected output:
{"city": "சென்னை"}
{"city": "சென்னை"}
Both lines represent the same data; the second is easier for humans to read.
Reading and Writing JSON Files
The functions without the "s" — json.dump() and json.load() — work directly with files.
import json
settings = {"theme": "dark", "font_size": 14}
# Write a Python dictionary to a JSON file
with open("settings.json", "w", encoding="utf-8") as file:
json.dump(settings, file, indent=4)
# Read the JSON file back into a dictionary
with open("settings.json", "r", encoding="utf-8") as file:
loaded = json.load(file)
print(loaded["theme"])
Expected output:
dark
| Function | Works With |
|---|---|
json.dumps() / json.loads() | Strings |
json.dump() / json.load() | Files |
File handling and the with statement are covered in the Python File Handling lessons.
Common Mistakes
| Mistake | Problem |
|---|---|
| Using single quotes in JSON text | JSONDecodeError — JSON requires double quotes |
Writing True, False, None in JSON text | Invalid JSON — use true, false, null |
Treating dumps() output as a dictionary | It is a string; use loads() to get a dictionary |
Mixing up load/loads and dump/dumps | The "s" versions work with strings; the others work with files |
Serializing sets or datetime objects | TypeError — convert to a list or string first |
| Expecting tuples back after parsing | Tuples become lists |
Related Concepts
- Python Dictionaries — the Python structure that maps to JSON objects
- Python Lists — the Python structure that maps to JSON arrays
- Python File Handling — saving and loading JSON files
- Python Exception Handling — handling
JSONDecodeError