How to read and write JSON files in Python

Answered
Jan 05, 2026 610 views 1 answers
8

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

D
Asked by devops_guru
Gold 290 rep

1 Answer

5

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)
A
Answered by ahmed_tech 1 week, 2 days ago
Platinum 151 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.