Skip to content

Q&A · Answered

How to read and write JSON files in Python

asked 9 months, 1 week ago 1031 views 1 answer
8

What is the best way to read JSON data from a file and write JSON to a file in Python?

1 Answer

One accepted
5

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago

Reading JSON

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)

Writing JSON

# 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)

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.