In Python, the json module provides functions for encoding and decoding JSON data. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. Here's an overview of how to work with JSON in Python using the json module:
To use the functionalities provided by the json module, you need to import it:
import json
The json module provides the json.dumps() function to serialize Python objects (such as dictionaries and lists) into JSON format:
data = {"name": "John", "age": 30, "city": "New York"}
json_data = json.dumps(data)
print(json_data) # Output: {"name": "John", "age": 30, "city": "New York"}
The json module provides the json.loads() function to deserialize JSON data into Python objects:
json_data = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_data)
print(data) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
You can use the json.dump() and json.load() functions to read from and write to JSON files:
Writing JSON data to a file
with open("data.json", "w") as json_file:
json.dump(data, json_file)
Reading JSON data from a file
with open("data.json", "r") as json_file:
loaded_data = json.load(json_file)
print(loaded_data) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
The json module can handle most built-in Python data types, including dictionaries, lists, strings, integers, floats, booleans, and None. However, it does not support more complex data types such as custom objects, functions, or file objects.
You can implement custom serialization and deserialization using the default and object_hook parameters of the json.dumps() and json.loads() functions, respectively.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def encode_person(obj):
if isinstance(obj, Person):
return {"name": obj.name, "age": obj.age}
return obj
def decode_person(dct):
if "name" in dct and "age" in dct:
return Person(dct["name"], dct["age"])
return dct
Custom serialization and deserialization
person = Person("Alice", 25)
encoded_person = json.dumps(person, default=encode_person)
decoded_person = json.loads(encoded_person, object_hook=decode_person)
print(decoded_person.name, decoded_person.age) # Output: Alice 25
The json module is a powerful tool for working with JSON data in Python. It allows you to easily encode and decode JSON data, read from and write to JSON files, and handle various data types, making it a convenient choice for data interchange in Python applications.