Working with JSON Data in Python
JSON (JavaScript Object Nottation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. Python provides a built-in json module for handling JSON data. Using the json module, you can convert Python objects to JSON strings (serialization) and convert JSON strings to Python objects (deserialization).
Basic Concepts
- Serialization: Converting Python objects to JSON strings.
- Deserialization: Converting JSON strings to Python objects.
- Python Object to JSON Data Mapping:
dictcorresponds to JSON objects ({})listandtuplecorrespond to JSON arrays ([])strcorresponds to JSON strings ("")int,float, andboolcorrespond to JSON numbers and boolean valuesNonecorresponds to JSONnull
Examples
Let's explore some practical examples to understand how to use the json module.
Example 1: Serializing Python Objects to JSON Strings
import json
# Python object
user_data = {
"username": "Alice",
"user_age": 30,
"student_status": False,
"enrolled_courses": ["Mathematics", "Physics"],
"user_address": {
"street_address": "123 Main Street",
"city_name": "Anytown"
}
}
# Serialize to JSON string
json_string = json.dumps(user_data)
print(json_string)
In this example, we use the json.dumps() method to serialize a Python dictionary object into a JSON string.
Example 2: Deserializing JSON Strings to Python Objects
import json
# JSON string
json_string = '{"username": "Alice", "user_age": 30, "student_status": false, "enrolled_courses": ["Mathematics", "Physics"], "user_address": {"street_address": "123 Main Street", "city_name": "Anytown"}}'
# Deserialize to Python object
parsed_data = json.loads(json_string)
print(parsed_data)
In this example, we use the json.loads() method to deserialize a JSON string into a Python dictionary object.
Example 3: Working with JSON Files
You can use the json module to read from and write to JSON files.
import json
# Write to JSON file
user_info = {
"username": "Alice",
"user_age": 30,
"student_status": False,
"enrolled_courses": ["Mathematics", "Physics"],
"user_address": {
"street_address": "123 Main Street",
"city_name": "Anytown"
}
}
with open('user_data.json', 'w') as file:
json.dump(user_info, file)
# Read from JSON file
with open('user_data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)
In this example, we use json.dump() to write a Python object to a JSON file and json.load() to read a Python object from a JSON file.
Advanced Features
The json module also provides advanced functionality, including:
- Custom serialization and deserialization: Use the
defaultandobject_hookparameters to customize serialization and deserialization behavior. - Sorting and indentation: Control JSON string formatting with the
sort_keysandindentparameters.
Here's a example of custom serialization and deserialization:
import json
# Custom serializer
def custom_serializer(obj):
if isinstance(obj, complex):
return {"__complex_number__": True, "real_part": obj.real, "imaginary_part": obj.imag}
raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")
# Custom deserializer
def custom_deserializer(dictionary):
if "__complex_number__" in dictionary:
return complex(dictionary["real_part"], dictionary["imaginary_part"])
return dictionary
# Using custom serialization and deserialization
complex_data = {
"username": "Alice",
"user_age": 30,
"student_status": False,
"enrolled_courses": ["Mathematics", "Physics"],
"user_address": {
"street_address": "123 Main Street",
"city_name": "Anytown"
},
"complex_value": complex(3, 4)
}
# Serialize to JSON string
json_output = json.dumps(complex_data, default=custom_serializer)
print(json_output)
# Deserialize to Python object
restored_data = json.loads(json_output, object_hook=custom_deserializer)
print(restored_data)
In this example, we use the default and object_hook parameters to customize serialization and deserialization behavior, allowing complex type objects to be properly handled.