How to read and write JSON in Python
How to read JSON in Python from a file
import json
with open('data.json') as f:
data = json.load(f)
print(data)
How to write JSON in Python to a file
import json
data = {
'name': 'John',
'age': 30,
'city': 'New York'
}
with open('data.json', 'w') as f:
json.dump(data, f)
How to read JSON in Python from a string
import json
data = json.loads('{"name": "John", "age": 30, "city": "New York"}')
print(data)
How to write JSON in Python to a string
import json
data = {
'name': 'John',
'age': 30,
'city': 'New York'
}
json_string = json.dumps(data)
print(json_string)
json_string = json.dumps(data, indent=4)
print(json_string)
Where to go next: