The json module in Python provides an easy way to encode and decode data in JSON (JavaScript Object Notation) format. JSON is a lightweight data interchange format that is widely used in web applications to transmit data between the server and the client.
The json module provides two main methods:
- json.dumps(): Converts a Python object into a JSON string.
- json.loads(): Converts a JSON string into a Python object.
For example, to convert a Python dictionary into a JSON string, you can use the dumps() method:
import json data = {'name': 'John', 'age': 30, 'city': 'New York'} json_string = json.dumps(data) print(json_string) # {"name": "John", "age": 30, "city": "New York"}
And to convert a JSON string into a Python object, you can use the loads() method:
import json json_string = '{"name": "John", "age": 30, "city": "New York"}' data = json.loads(json_string) print(data) # {'name': 'John', 'age': 30, 'city': 'New York'}
The json module also provides other functions for more advanced JSON processing, such as json.dump() and json.load() for reading and writing JSON data from files, and the json.JSONEncoder and json.JSONDecoder classes for custom JSON encoding and decoding.
0 Comments