JSON (JavaScript Object Notation) is a format for storing and exchanging structured data. Python provides the built-in json module, which makes it easy to read JSON data from a file and convert it into Python objects such as dictionaries and lists.
Suppose the file employees.json contains the following JSON data:
{
"employees": [
{
"name": "Liam",
"department": "Engineering"
},
{
"name": "Sophia",
"department": "Marketing"
}
]
}
import json
with open("employees.json", "r") as file:
data = json.load(file)
print(data)
Output
{
'employees': [
{'name': 'Liam', 'department': 'Engineering'},
{'name': 'Sophia', 'department': 'Marketing'}
]
}
Explanation:
- open("employees.json", "r") opens the JSON file in read mode.
- json.load(file) reads the JSON content and converts it into a Python dictionary.
Reading Specific Values from JSON
After reading a JSON file, the data is converted into Python objects such as dictionaries and lists. We can then access specific values using dictionary keys and list indexes, just like working with normal Python data structures.
import json
with open("employees.json", "r") as file:
data = json.load(file)
print(data["employees"][0]["name"])
Output
Liam
Explanation:
- data["employees"] accesses the value associated with the "employees" key, which is a list of employee records.
- [0] selects the first employee from the list.
- ["name"] retrieves the value of the "name" key from that employee's record.
Iterating Through JSON Data
JSON files often contain multiple records stored inside arrays. Instead of accessing each record manually, we can use a loop to process all records one by one.
import json
with open("employees.json", "r") as file:
data = json.load(file)
for employee in data["employees"]:
print(employee["name"], "-", employee["department"])
Output
Liam - Engineering
Sophia - Marketing
Explanation:
- data["employees"] returns the list containing all employee records.
- The for loop iterates through each employee dictionary in the list.
- employee["name"] retrieves the employee's name.
- employee["department"] retrieves the employee's department.
Error Handling While Reading JSON
When reading JSON files, errors may occur if the file is missing or if the JSON data is not properly formatted. Using try-except blocks helps handle these situations gracefully and prevents the program from terminating unexpectedly.
1. Handling FileNotFoundError: A FileNotFoundError occurs when Python cannot find the specified JSON file. Instead of crashing, we can display a user-friendly message.
import json
try:
with open("data.json", "r") as file:
data = json.load(file)
print("File data =", data)
except FileNotFoundError:
print("Error: 'data.json' file was not found.")
Output (if file is missing)
Error: 'data.json' file was not found.
Explanation:
- open("data.json", "r") opens the JSON file in read mode.
- json.load(file) reads and converts JSON data into a Python object.
- The try block executes the file-reading code. If the file does not exist, Python raises a FileNotFoundError.
- The except FileNotFoundError block catches the error and displays a meaningful message instead of showing a traceback.
2. Handling JSONDecodeError: A JSONDecodeError occurs when the JSON file contains invalid or improperly formatted JSON data.
import json
try:
with open("data.json", "r") as file:
data = json.load(file)
print("File data =", data)
except json.JSONDecodeError:
print("Error: Invalid JSON format in the file.")
Output (if JSON is malformed)
Error: Invalid JSON format in the file.
Explanation:
- json.load() expects the file content to follow valid JSON syntax.
- If the JSON data contains errors such as missing commas, unmatched braces or incorrect quotes, Python raises a JSONDecodeError.
- The except json.JSONDecodeError block catches the error and displays a clear message.
- This helps identify JSON formatting issues without crashing the program.