Python provides the built-in json module to easily work with JSON data — allowing you to convert between Python objects and JSON strings seamlessly.
What is JSON?
JSON is a lightweight, text-based format for storing and transferring data. It's commonly used in APIs, web applications, and configuration files.- JSON data is written as key–value pairs.
- It looks similar to Python dictionaries but uses specific syntax rules.
Example of JSON data:
{
"name": "Alice",
"age": 25,
"skills": ["Python", "Django", "Machine Learning"],
"isStudent": false
}
Importing the JSON Module
To work with JSON in Python, import the json module:import json
The json module provides the following key methods:
| Function | Description |
|---|---|
| json.load() | Read JSON data from a file |
| json.loads() | Parse JSON string to Python object |
| json.dump() | Write Python object to a JSON file |
| json.dumps() | Convert Python object to JSON string |
Converting JSON to Python (Deserialization)
Deserialization means converting JSON data into Python objects. Example using json.loads() (string to Python object):import json
json_data = '{"name": "Alice", "age": 25, "isStudent": false}'
python_obj = json.loads(json_data)
print(python_obj)
print(type(python_obj))
Output:
{'name': 'Alice', 'age': 25, 'isStudent': False}
<class 'dict'>
Reading JSON from a File
If JSON data is stored in a file, use json.load():import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
The with statement ensures the file is properly closed after reading.The function automatically parses the file content into a Python object (like a dict or list).
Converting Python to JSON (Serialization)
Serialization means converting a Python object into JSON data.Example using json.dumps():
import json
data = {
"name": "Bob",
"age": 30,
"languages": ["Python", "C++"],
"isStudent": False
}
json_string = json.dumps(data)
print(json_string)
Output:
{"name": "Bob", "age": 30, "languages": ["Python", "C++"], "isStudent": false}
Writing JSON to a File
To write a Python object as JSON to a file, use json.dump():import json
data = {"course": "Python", "level": "Intermediate", "duration": "30 hours"}
with open("course.json", "w") as file:
json.dump(data, file)
This creates a file named course.json with properly formatted JSON data.
Pretty Printing JSON
By default, JSON output is compact. You can format it neatly for readability using indent and sort_keys parameters.import json
data = {"course": "Python", "level": "Intermediate", "duration": "30 hours"}
json_string = json.dumps(data, indent=4, sort_keys=True)
print(json_string)
Output:
{
"course": "Python",
"duration": "30 hours",
"level": "Intermediate"
}
Handling Complex Data Types
The json module supports basic types like dict, list, str, int, float, bool, and None. However, some Python objects (like sets, tuples, or custom classes) need to be converted manually.Example — handling unsupported types:
import json
data = {"numbers": {1, 2, 3}}
# Convert set to list before dumping
json_string = json.dumps({"numbers": list(data["numbers"])})
print(json_string)
Output:
{"numbers": [1, 2, 3]}
Converting Between JSON and Custom Classes
Sometimes you may want to convert custom class objects into JSON.import json
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def encode_student(obj):
if isinstance(obj, Student):
return {"name": obj.name, "age": obj.age}
raise TypeError(f"Object {obj} not serializable")
s1 = Student("Alice", 21)
json_data = json.dumps(s1, default=encode_student)
print(json_data)
Output:
{"name": "Alice", "age": 21}
JSON Error Handling
While parsing, invalid JSON strings can raise exceptions. Always use try-except blocks to handle errors gracefully.import json
try:
data = json.loads('{"name": "Alice", "age": 25,}') # invalid JSON
except json.JSONDecodeError as e:
print("Error parsing JSON:", e)
Output:
Error parsing JSON: Illegal trailing comma before end of object: line 1 column 28 (char 27)
Summary
JSON handling is an essential skill for any Python developer working with APIs, web applications, or data serialization. By mastering the json module, you can efficiently read, write, and exchange structured data between systems — making your programs both versatile and web-ready.| Concept | Description |
|---|---|
| json.loads() | Converts JSON string to Python object |
| json.load() | Reads JSON data from a file |
| json.dumps() | Converts Python object to JSON string |
| json.dump() | Writes JSON data to a file |
| indent | Makes JSON human-readable |
| default | Converts unsupported objects like custom classes |
| JSONDecodeError | Raised when JSON data is invalid |