Working with JSON Data
Now that we know how to properly import the JSON module, let's explore how to use it for common JSON operations.
Creating a Complete JSON Example
Create a new file named json_operations.py
with the following content:
## Complete example of working with JSON in Python
import json
## 1. Converting Python object to JSON string (serialization)
user = {
"name": "Charlie",
"age": 28,
"is_student": False,
"courses": ["Python", "Data Science", "Web Development"],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
## Convert Python dictionary to JSON string
json_string = json.dumps(user, indent=2)
print("JSON string created from Python object:")
print(json_string)
print("\n" + "-"*50 + "\n")
## 2. Parse JSON string to Python object (deserialization)
parsed_user = json.loads(json_string)
print("Python object created from JSON string:")
print("Name:", parsed_user["name"])
print("Age:", parsed_user["age"])
print("Courses:", parsed_user["courses"])
print("City:", parsed_user["address"]["city"])
print("\n" + "-"*50 + "\n")
## 3. Writing JSON to a file
with open("/home/labex/project/user_data.json", "w") as json_file:
json.dump(user, json_file, indent=2)
print("JSON data written to user_data.json")
## 4. Reading JSON from a file
with open("/home/labex/project/user_data.json", "r") as json_file:
loaded_user = json.load(json_file)
print("JSON data loaded from file. User name:", loaded_user["name"])
This script demonstrates four common JSON operations:
- Converting a Python object to a JSON string using
json.dumps()
- Parsing a JSON string into a Python object using
json.loads()
- Writing JSON data to a file using
json.dump()
- Reading JSON data from a file using
json.load()
Run the script:
python3 /home/labex/project/json_operations.py
You should see output similar to:
JSON string created from Python object:
{
"name": "Charlie",
"age": 28,
"is_student": false,
"courses": [
"Python",
"Data Science",
"Web Development"
],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
--------------------------------------------------
Python object created from JSON string:
Name: Charlie
Age: 28
Courses: ['Python', 'Data Science', 'Web Development']
City: Boston
--------------------------------------------------
JSON data written to user_data.json
JSON data loaded from file. User name: Charlie
The script also created a file named user_data.json
. Let's look at its contents:
cat /home/labex/project/user_data.json
You should see the JSON data formatted with proper indentation:
{
"name": "Charlie",
"age": 28,
"is_student": false,
"courses": ["Python", "Data Science", "Web Development"],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
You have now successfully learned how to work with JSON data in Python, including how to avoid the NameError: name 'json' is not defined
error by properly importing the module.