use the json
module to easily serialize and deserialize JSON data in Python. JSON is a widely-used data format that's easy to read and write, and the json
module makes it simple to work with JSON data in Python. Here's an example:
import json
# serialize a Python object to JSON
data = {'name': 'Alice', 'age': 25}
json_data = json.dumps(data)
print(json_data)
# deserialize JSON data to a Python object
json_data = '{"name": "Bob", "age": 30}'
data = json.loads(json_data)
print(data)
This will output:
{"name": "Alice", "age": 25}
{'name': 'Bob', 'age': 30}
In this example, we used the dumps
method to serialize a Python object (data
) to a JSON-formatted string (json_data
). We then used the loads
method to deserialize a JSON-formatted string (json_data
) to a Python object (data
). This makes it easy to work with JSON data in Python, whether you're reading from or writing to a file, or sending data over the web.
Top comments (0)