The json
module in Python provides functions for serializing and deserializing JSON (JavaScript Object Notation). JSON is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.
Table of Contents
- Introduction
- Key Functions
json.dump
json.dumps
json.load
json.loads
- Customization and Extending JSON
- Custom Serialization
- Custom Deserialization
- Examples
- Writing JSON to a File
- Reading JSON from a File
- Serializing a Python Object to JSON
- Deserializing a JSON String to a Python Object
- Custom JSON Encoder
- Custom JSON Decoder
- Real-World Use Case
- Conclusion
- References
Introduction
The json
module provides an easy way to encode and decode data in JSON format. It is commonly used for data interchange between systems and applications.
Key Functions
json.dump
Serializes a Python object and writes it to a file.
import json
user = {'id': 1, 'firstName': 'John', 'lastName': 'Doe', 'email': 'john.doe@example.com'}
with open('user.json', 'w') as f:
json.dump(user, f)
json.dumps
Serializes a Python object to a JSON formatted string.
import json
user = {'id': 1, 'firstName': 'John', 'lastName': 'Doe', 'email': 'john.doe@example.com'}
json_string = json.dumps(user)
print(json_string)
Output:
{"id": 1, "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com"}
json.load
Deserializes a JSON formatted file to a Python object.
import json
with open('user.json', 'r') as f:
user = json.load(f)
print(user)
Output:
{'id': 1, 'firstName': 'John', 'lastName': 'Doe', 'email': 'john.doe@example.com'}
json.loads
Deserializes a JSON formatted string to a Python object.
import json
json_string = '{"id": 1, "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com"}'
user = json.loads(json_string)
print(user)
Output:
{'id': 1, 'firstName': 'John', 'lastName': 'Doe', 'email': 'john.doe@example.com'}
Customization and Extending JSON
Custom Serialization
You can define a custom encoder to handle complex Python objects.
import json
class User:
def __init__(self, id, firstName, lastName, email):
self.id = id
self.firstName = firstName
self.lastName = lastName
self.email = email
def user_encoder(obj):
if isinstance(obj, User):
return {'id': obj.id, 'firstName': obj.firstName, 'lastName': obj.lastName, 'email': obj.email}
return json.JSONEncoder.default(obj)
user = User(1, 'John', 'Doe', 'john.doe@example.com')
json_string = json.dumps(user, default=user_encoder)
print(json_string)
Output:
{"id": 1, "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com"}
Custom Deserialization
You can define a custom decoder to handle complex JSON data.
import json
class User:
def __init__(self, id, firstName, lastName, email):
self.id = id
self.firstName = firstName
self.lastName = lastName
self.email = email
def user_decoder(dct):
if 'id' in dct and 'firstName' in dct and 'lastName' in dct and 'email' in dct:
return User(dct['id'], dct['firstName'], dct['lastName'], dct['email'])
return dct
json_string = '{"id": 1, "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com"}'
user = json.loads(json_string, object_hook=user_decoder)
print(user.id, user.firstName, user.lastName, user.email)
Output:
1 John Doe john.doe@example.com
Examples
Writing JSON to a File
import json
product = {'id': 101, 'name': 'Laptop', 'price': 999.99, 'description': 'A high-performance laptop.'}
with open('product.json', 'w') as f:
json.dump(product, f)
Reading JSON from a File
import json
with open('product.json', 'r') as f:
product = json.load(f)
print(product)
Output:
{'id': 101, 'name': 'Laptop', 'price': 999.99, 'description': 'A high-performance laptop.'}
Serializing a Python Object to JSON
import json
product = {'id': 101, 'name': 'Laptop', 'price': 999.99, 'description': 'A high-performance laptop.'}
json_string = json.dumps(product)
print(json_string)
Output:
{"id": 101, "name": "Laptop", "price": 999.99, "description": "A high-performance laptop."}
Deserializing a JSON String to a Python Object
import json
json_string = '{"id": 101, "name": "Laptop", "price": 999.99, "description": "A high-performance laptop."}'
product = json.loads(json_string)
print(product)
Output:
{'id': 101, 'name': 'Laptop', 'price': 999.99, 'description': 'A high-performance laptop.'}
Custom JSON Encoder
import json
class Product:
def __init__(self, id, name, price, description):
self.id = id
self.name = name
self.price = price
self.description = description
class ProductEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Product):
return {'id': obj.id, 'name': obj.name, 'price': obj.price, 'description': obj.description}
return json.JSONEncoder.default(self, obj)
product = Product(101, 'Laptop', 999.99, 'A high-performance laptop.')
json_string = json.dumps(product, cls=ProductEncoder)
print(json_string)
Output:
{"id": 101, "name": "Laptop", "price": 999.99, "description": "A high-performance laptop."}
Custom JSON Decoder
import json
class Product:
def __init__(self, id, name, price, description):
self.id = id
self.name = name
self.price = price
self.description = description
def product_decoder(dct):
if 'id' in dct and 'name' in dct and 'price' in dct and 'description' in dct:
return Product(dct['id'], dct['name'], dct['price'], dct['description'])
return dct
json_string = '{"id": 101, "name": "Laptop", "price": 999.99, "description": "A high-performance laptop."}'
product = json.loads(json_string, object_hook=product_decoder)
print(product.id, product.name, product.price, product.description)
Output:
101 Laptop 999.99 A high-performance laptop.
Real-World Use Case
Configuration File Handling
JSON is commonly used for configuration files. Here is an example of reading and writing a configuration file in JSON format.
import json
config = {
'database': {
'host': 'localhost',
'port': 3306,
'user': 'admin',
'password': 'admin123'
},
'debug': True
}
# Writing configuration to a file
with open('config.json', 'w') as f:
json.dump(config, f, indent=4)
# Reading configuration from a file
with open('config.json', 'r') as f:
config = json.load(f)
print(config)
Output:
{
"database": {
"host": "localhost",
"port": 3306,
"user": "admin",
"password": "admin123"
},
"debug": true
}
Conclusion
The json
module in Python provides an easy and efficient way to work with JSON data. It supports serializing and deserializing Python objects to and from JSON, making it a versatile tool for data interchange and configuration management.