Introduction
JSON (JavaScript Object Notation) is one of the most popular data formats used in modern software development. It is lightweight, easy to read, and supported by almost every programming language. JSON is commonly used for storing data, exchanging information between applications, and communicating with web APIs.
In Python, JSON file handling allows developers to read data from JSON files, write data into JSON files, update existing data, and convert Python objects into JSON format. Because JSON closely resembles Python dictionaries and lists, working with JSON in Python is simple and efficient.
What is Python JSON File Handling?
Python JSON File Handling refers to the process of reading, writing, parsing, and managing JSON data using Python.
Note: JSON stores information in key-value pairs.
Example JSON Data:
{
"name": "John",
"age": 25,
"city": "New York"
}
Python provides a built-in module called json that helps developers work with JSON files easily.
Common JSON operations include:
- Reading JSON files
- Writing JSON files
- Converting Python objects to JSON
- Converting JSON data to Python objects
- Updating JSON records
JSON is widely used because it is:
- Lightweight
- Human-readable
- Easy to parse
- Language-independent
- Commonly used in APIs
Importing the JSON Module
Before working with JSON files, import the json module.
import json
The json module contains functions for reading and writing JSON data.
Understanding JSON Structure
A JSON object consists of key-value pairs.
Example:
{
"name": "Alice",
"age": 30,
"city": "London"
}
Equivalent Python Dictionary:
{
"name": "Alice",
"age": 30,
"city": "London"
}
Because of this similarity, Python can easily convert between JSON and dictionaries.
Syntax
Reading a JSON File
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
Writing a JSON File
import json
data = {
"name": "John",
"age": 25
}
with open("data.json", "w") as file:
json.dump(data, file)
Reading JSON Files
The json.load() function reads JSON data from a file and converts it into a Python object.
Example:
JSON File:
{
"name": "John",
"age": 25,
"city": "New York"
}
Python Code:
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
Output:
The JSON object becomes a Python dictionary.
Accessing JSON Values
After loading JSON data, values can be accessed like a dictionary.
Example:
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data["name"])
print(data["age"])
Output:
25
Reading Nested JSON Data
JSON often contains nested objects.
Example JSON:
{
"student": {
"name": "Rahul",
"age": 20
}
}
Python Code:
import json
with open("student.json", "r") as file:
data = json.load(file)
print(data["student"]["name"])
Output:
Writing JSON Files
The json.dump() function writes Python data into a JSON file.
Example:
import json
student = {
"name": "John",
"age": 25,
"city": "New York"
}
with open("student.json", "w") as file:
json.dump(student, file)
Output JSON:
Writing Formatted JSON
For better readability, use the indent parameter.
Example:
import json
student = {
"name": "John",
"age": 25,
"city": "New York"
}
with open("student.json", "w") as file:
json.dump(student, file, indent=4)
Output:
The file becomes easier to read.
Converting Python Objects to JSON Strings
The json.dumps() function converts Python objects into JSON strings.
Example:
import json
student = {
"name": "Alice",
"age": 30
}
json_data = json.dumps(student)
print(json_data)
Output:
Converting JSON Strings to Python Objects
The json.loads() function converts JSON strings into Python objects.
Example:
import json
json_data = '{"name":"John","age":25}'
data = json.loads(json_data)
print(data)
Output:
Updating JSON Files
JSON files can be modified by reading, updating, and writing them again
Example:
import json
with open("student.json", "r") as file:
data = json.load(file)
data["age"] = 26
with open("student.json", "w") as file:
json.dump(data, file, indent=4)
Updated JSON:
Example
Suppose you want to store employee information.
import json
employee = {
"id": 101,
"name": "Alice",
"department": "IT"
}
with open("employee.json", "w") as file:
json.dump(employee, file, indent=4)
Output:
Real-life Example
Imagine you are building a student management system.
Each student record is stored in JSON format.
import json
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
with open("student.json", "w") as file:
json.dump(student, file, indent=4)
print("Student record saved.")
Output:
Generated JSON File:
{
"name": "Rahul",
"age": 20,
"course": "Python"
}
Common Mistakes
1. Forgetting to Import json Module
Incorrect:
data = json.load(file)
Output:
Correct:
import json
2. Using load() Instead of loads()
Incorrect:
json.load(json_string)
Correct:
Correct:
json.loads(json_string)
Remember:
| Function | Purpose |
|---|---|
| load() | Read from file |
| loads() | Read from string |
3. Using dump() Instead of dumps()
Incorrect:
json.dump(data)
Correct:
json.dumps(data)
Remember:
| Function | Purpose |
|---|---|
| dump() | Write to file |
| dumps() | Convert to string |
4. Invalid JSON Format
Incorrect:
{
name: "John"
}
Output:
Correct:
{
"name": "John"
}
Keys must use double quotes.
5. Not Handling Exceptions
Incorrect:
with open("data.json") as file:
data = json.load(file)
Correct:
import json
try:
with open("data.json") as file:
data = json.load(file)
except FileNotFoundError:
print("File not found")
Best Practices
1. Use the with Statement
with open("data.json") as file:
data = json.load(file)
Automatically closes the file.
2. Format JSON with Indentation
json.dump(data, file, indent=4)
Improves readability.
3. Validate JSON Data
Ensure data structure is correct before processing.
4. Handle Exceptions
try:
pass
except:
pass
Prevents application crashes.
5. Use Meaningful Keys
Good Example:
{
"student_name": "Rahul"
}
Better readability and maintenance.
Conclusion
Python JSON File Handling is a crucial skill for modern software development. The built-in json module makes it easy to read, write, update, and process JSON data efficiently. Functions such as json.load(), json.dump(), json.loads(), and json.dumps() provide powerful tools for working with structured data.
JSON is widely used in APIs, web applications, configuration files, and data storage because it is lightweight, easy to read, and platform-independent.
Python JSON File Handling – Interview Questions
Q 1: How do you read JSON files in Python?
Q 2: How do you write JSON files?
Q 3: What module is used for JSON in Python?
Q 4: Can Python dictionaries be converted to JSON?
Q 5: Can JSON support nested data structures?
Python JSON File Handling – Objective Questions (MCQs)
Q1. Which module is used to work with JSON in Python?
Q2. Which method converts a Python dictionary into a JSON string?
Q3. Which method reads a JSON object from a file?
Q4. Which method writes JSON data to a file?
Q5. What will json.loads('{"a":1}') return?