Read and Write JSON Files in Python


What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It's commonly used for APIs, configuration files, and data exchange between frontend and backend.

Python's json Module

Python provides the built-in json module to parse, read, write, and convert JSON data.

import json

Reading JSON from a File (Parse JSON)

Example JSON File (data.json):

{
  "name": "Alice",
  "age": 30,
  "is_student": false
}

Read JSON File in Python:

import json

with open("data.json", "r") as file:
    data = json.load(file)
    print(data)
    print(data["name"])  # Accessing key

Output:

{'name': 'Alice', 'age': 30, 'is_student': False}
Alice


Writing JSON to a File


Convert Python Dictionary to JSON:

import json

person = {
    "name": "Bob",
    "age": 25,
    "is_student": True
}

with open("output.json", "w") as file:
    json.dump(person, file, indent=4)

This creates a JSON file output.json with human-readable formatting using indent=4.

Content in output.json:

{
    "name": "Bob",
    "age": 25,
    "is_student": true
}


Convert Between JSON Strings and Python Objects


Convert Python to JSON String:

json_string = json.dumps(person, indent=2)
print(json_string)

Convert JSON String to Python Dictionary:

json_data = '{"name": "John", "age": 28}'
parsed = json.loads(json_data)
print(parsed["age"])

Example: Read, Modify, and Save JSON File

import json

# Read existing file
with open("data.json", "r") as f:
    data = json.load(f)

# Modify data
data["age"] += 1

# Write back to file
with open("data.json", "w") as f:
    json.dump(data, f, indent=4)

Best Practices for JSON in Python

  • Always use with open() to safely handle files.
  • Use indent for readable formatting.
  • Use try-except for error handling when parsing large JSON files.
  • Use .get() when accessing keys to avoid KeyError.