JSON (JavaScript Object Notation) is a lightweight, text-based format used to store and exchange structured data between applications. Python provides a built-in json module for reading, writing, encoding, and decoding JSON data.
Example:
{
"name": "Aarav",
"age": 22,
"skills": ["Python", "SQL"],
"is_student": true,
"address": null
}
Explanation:
- Curly braces represent a JSON object.
- Square brackets [] represent an array.
- Property names and string values use double quotation marks.
- Boolean values are written as true or false, while null represents an absent or null value.
- JSON does not support comments or trailing commas.
Importing JSON Module
Python includes the json module in its standard library. No external package installation is required.
import json
print("JSON module imported successfully")
Explanation:
- Import json makes the module's functions available.
- Module provides methods for converting between JSON data and Python objects.
Python Data Types and JSON Conversion
json module converts supported Python values into their corresponding JSON representations.
Python type or value | JSON equivalent |
|---|---|
dict | Object |
list, tuple | Array |
str | String |
int, float | Number |
True | true |
False | false |
None | null |
Explanation:
- JSON objects use string property names.
- Tuples become JSON arrays when serialized.
- JSON objects and arrays normally become Python dictionaries and lists when decoded.
- Sets and arbitrary custom objects are not directly serializable by default.
Parsing JSON in Python
Parsing converts JSON text into Python objects so that program can access and process the data. It provides two main functions for this purpose: json.loads() and json.load().
1. Converting a JSON String in to a Python Cheet
json.loads() function parses a JSON-formatted string and returns the corresponding Python object.
import json
json_text = '{"name": "Aarav", "age": 22, "is_student": true}'
student = json.loads(json_text)
print(student)
print(student["name"])
print(type(student))
Output
{'name': 'Aarav', 'age': 22, 'is_student': True}
Aarav
<class 'dict'>
Explanation:
- json.loads() converts the JSON string into a Python dictionary.
- student["name"] retrieves the value associated with the name key.
- Resulting data type is dict because the JSON input contains an object.
2. Reading a JSON File
json.load() function reads JSON content from an open file and converts it into a Python object. Suppose a file named students.json contains:
{
"name": "Aarav",
"subjects": ["Python", "SQL"],
"active": true
}
Python Program:
import json
with open("students.json", "r", encoding="utf-8") as file:
student = json.load(file)
print(student)
print(student["subjects"][0])
Output
{'name': 'Aarav', 'subjects': ['Python', 'SQL'], 'active': True}
Python
Explanation:
- open() opens the file in read mode using UTF-8 encoding.
- json.load() parses its contents into Python data structures.
- student["subjects"][0] retrieves the first subject from the list.
- With statement automatically closes the file after processing.
Converting Python Objects into JSON
It provides json.dumps() and json.dump() to serialize supported objects into JSON representations. Serialization means converting a Python object into JSON-formatted data.
1. Converting a Python Object into a JSON String
json.dumps() function converts a Python object into a JSON-formatted string.
import json
student = {
"name": "Aarav",
"age": 22,
"active": True,
"score": None
}
json_text = json.dumps(student)
print(json_text)
print(type(json_text))
Output
{"name": "Aarav", "age": 22, "active": true, "score": null}
<class 'str'>
Explanation:
- json.dumps() serializes the dictionary into a JSON string.
- Python's True becomes JSON true, and None becomes JSON null.
- Result is a string, not a dictionary.
2. Writing JSON Data to a File
json.dump() function serializes a Python object directly into an open file.
import json
student = {
"name": "Aarav",
"age": 22,
"subjects": ["Python", "SQL"]
}
with open("student.json", "w", encoding="utf-8") as file:
json.dump(student, file, indent=4)
Explanation:
- json.dump() writes the serialized data directly to the file.
- w mode creates the file if it does not exist and replaces its existing contents if it does.
- Indent parameter makes the output easier to read.
- Function does not print the JSON content to the console automatically.
Formatting and Sorting in JSON
JSON output can be made easier to read by using formatting options provided by json.dumps() and json.dump(). The indent parameter controls indentation, while sort_keys=True sorts object keys in the serialized output.
import json
data = {
"zebra": 3,
"apple": 1,
"mango": 2
}
formatted_json = json.dumps(data, indent=4, sort_keys=True)
print(formatted_json)
Output:

Explanation:
- indent=4 adds four spaces of indentation at each nesting level.
- sort_keys=True sorts dictionary keys in the output.
- These parameters change the presentation of the serialized data, not its underlying values.
Handling JSON Errors
Invalid JSON syntax can raise json.JSONDecodeError during parsing. File operations may raise FileNotFoundError, while unsupported objects during serialization can raise TypeError.
import json
try:
with open("students.json", "r", encoding="utf-8") as file:
student = json.load(file)
print(student)
except FileNotFoundError:
print("Error: students.json was not found.")
except json.JSONDecodeError:
print("Error: The file contains invalid JSON.")
Output
Error: students.json was not found.
Explanation:
- try block contains the file-reading and parsing operations.
- FileNotFoundError handles a missing file.
- json.JSONDecodeError handles malformed JSON content.
- Separating these exceptions makes it easier to identify and correct common problems.
Complete Example
Following program combines file writing, file reading, data modification, and serialization in one workflow.
import json
filename = "student.json"
student = {
"name": "Aarav",
"age": 22,
"skills": ["Python", "SQL"]
}
with open(filename, "w", encoding="utf-8") as file:
json.dump(student, file, indent=4)
with open(filename, "r", encoding="utf-8") as file:
loaded_student = json.load(file)
loaded_student["skills"].append("JSON")
with open(filename, "w", encoding="utf-8") as file:
json.dump(loaded_student, file, indent=4)
print(loaded_student["name"])
print(loaded_student["skills"])
Output
Aarav
['Python', 'SQL', 'JSON']
Explanation:
- json.dump() saves the initial dictionary in the file.
- json.load() reconstructs the Python dictionary from the saved JSON data.
- append() method adds JSON to the skills list.
- Second json.dump() call saves the modified dictionary, replacing the earlier file contents.