JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. Python provides a built-in module called json
to work with JSON data.
You can use json.dumps()
to convert a Python object into a JSON string and json.loads()
to convert a JSON string back into a Python object:
import json
data = {"name": "Alice", "age": 25}
json_data = json.dumps(data) # Convert Python object to JSON string
print("JSON data:", json_data)
python_obj = json.loads(json_data) # Convert JSON string to Python object
print("Python object:", python_obj)
This code demonstrates how to serialize a Python object into JSON and then deserialize it back into a Python object.
Write a Python program that reads a JSON file containing information about a person and prints the name and age of the person.
Answers: Use json.dumps()
to convert a Python object into a JSON string. Use json.loads()
to convert a JSON string back into a Python object.