Python JSON Tutorial: Convert, Parse, Write
In Python, the json module can be used to manipulate JSON data. You can utilize the following methods to use the json module:
- Convert Python objects to JSON strings.
import json
data = {'name': 'John', 'age': 30, 'city': 'New York'}
json_string = json.dumps(data)
print(json_string)
- Convert a JSON string to a Python object.
import json
json_string = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_string)
print(data)
- Write JSON data to a file.
import json
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as f:
json.dump(data, f)
- Read JSON data from a file.
import json
with open('data.json', 'r') as f:
data = json.load(f)
print(data)
These are the basic methods for handling JSON data using the json module. You can further explore the functionality and methods of the json module as needed.