8
What is the best way to read JSON data from a file and write JSON to a file in Python?
Loading...
Q&A · Answered
What is the best way to read JSON data from a file and write JSON to a file in Python?
Accepted answer
import json
# Read JSON file
with open('data.json', 'r') as f:
data = json.load(f)
# Read JSON string
json_string = '{"name": "John", "age": 30}'
data = json.loads(json_string)
# Write to file
data = {"name": "John", "age": 30}
with open('output.json', 'w') as f:
json.dump(data, f, indent=4)
# Convert to string
json_string = json.dumps(data, indent=2)Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.