JSON (JavaScript Object Notation) is a lightweight text format used to store and exchange structured data between applications. Python provides a built-in json module for reading, writing, parsing, and converting JSON data without installing an external package.
Understanding JSON
It represents structured data using objects, arrays, strings, numbers, Boolean values, and null. Python's json module converts JSON data into Python objects and vice versa.
{
"name": "Aarav",
"age": 22,
"skills": ["Python", "SQL"],
"is_student": true,
"address": null
}
Explanation:
- Objects contain key-value pairs enclosed in curly braces.
- Arrays contain ordered values enclosed in square brackets.
- JSON property names and string values use double quotation marks.
- JSON uses true, false, and null instead of Python's True, False, and None.
Parsing JSON strings
Parsing converts a JSON-formatted string into a Python object. The json.loads() function is used when JSON data is already available as a string.
import json
json_text = '{"name": "Aarav", "age": 22, "skills": ["Python", "SQL"]}'
data = json.loads(json_text)
print(data)
print(data["name"])
print(data["skills"][0])
Output
{'name': 'Aarav', 'age': 22, 'skills': ['Python', 'SQL']}
Aarav
Python
Explanation:
- json.loads() parses the JSON string and returns a Python dictionary.
- Dictionary keys provide access to individual values.
- List indexing retrieves items from the skills array.
Reading JSON data
json.load() function reads a JSON document from an open file and converts it into a Python object. Use a with statement to ensure that the file is closed automatically.
import json
with open("student.json", "r", encoding="utf-8") as file:
data = json.load(file)
print(data)
print(data["name"])
print(data["skills"])
Output
{'name': 'Aarav', 'age': 22, 'skills': ['Python', 'SQL']}
Aarav
['Python', 'SQL']
Explanation:
- open() opens the file in read mode.
- json.load() reads and parses the JSON document.
- Resulting dictionary supports normal Python operations, including key access and list indexing.
Converting Python Objects into JSON Strings
json.dumps() function serializes a Python object into a JSON-formatted string. This is useful when data needs to be prepared for transmission, logging, or further processing.
import json
data = {
"name": "Aarav",
"age": 22,
"skills": ["Python", "SQL"]
}
json_text = json.dumps(data, indent=4, sort_keys=True)
print(json_text)
print(type(json_text))
Output

Explanation:
- json.dumps() returns a string rather than writing directly to a file.
- indent=4 formats the output with four spaces per indentation level.
- sort_keys=True arranges object keys in sorted order.
- type() confirms that the resulting value is a Python string.
Writing JSON data
json.dump() function serializes a Python object and writes the JSON representation directly to an open file. This is useful for saving application settings, records, and processed data.
import json
data = {
"name": "Aarav",
"age": 22,
"skills": ["Python", "SQL"]
}
with open("output.json", "w", encoding="utf-8") as file:
json.dump(data, file, indent=4, ensure_ascii=False)
print("JSON data written successfully.")
Output
JSON data written successfully.
Explanation:
- json.dump() writes the serialized data into the file.
- write mode ("w") creates the file if it does not exist and replaces its existing contents if it does.
- indent=4 makes the file easier to read.
- ensure_ascii=False preserves non-ASCII characters directly in the output.
Loading Methods
Function | Purpose | Input | Result |
|---|---|---|---|
json.load() | Read and parse JSON | File object | Python object |
json.loads() | Parse a JSON document | JSON string | Python object |
json.dump() | Serialize and write JSON | Python object and file object | Writes to file |
json.dumps() | Serialize JSON | Python object | JSON string |
Handling JSON Errors
Invalid JSON can cause json.load() or json.loads() to raise a JSONDecodeError. File operations may also raise FileNotFoundError when the requested file is missing.
import json
json_text = '{"name": "Aarav", "age": }'
try:
data = json.loads(json_text)
print(data)
except json.JSONDecodeError as error:
print("Invalid JSON:", error.msg)
Output
Invalid JSON: Expecting value
Explanation:
- JSON string is invalid because age has no value.
- json.loads() raises JSONDecodeError when it cannot parse the document.
- Except block catches the exception and displays a meaningful message.