0
0
Pythonprogramming~5 mins

Working with JSON files in Python

Choose your learning style9 modes available
Introduction

JSON files let us save and share data in a simple text format. Working with JSON files helps programs read and write data easily.

Saving user settings so they stay after closing the program
Sharing data between different programs or websites
Storing lists or details like contacts or tasks
Loading data from a file to use in your program
Backing up information in a readable format
Syntax
Python
import json

# To read JSON from a file:
with open('file.json', 'r') as file:
    data = json.load(file)

# To write JSON to a file:
with open('file.json', 'w') as file:
    json.dump(data, file, indent=4)

Use json.load() to read JSON data from a file and convert it into Python objects.

Use json.dump() to write Python objects as JSON into a file. The indent parameter makes the file easy to read.

Examples
This reads JSON from 'data.json' and prints the Python data.
Python
import json

# Reading JSON data from a file
with open('data.json', 'r') as f:
    info = json.load(f)
print(info)
This saves the person dictionary into 'person.json' with nice formatting.
Python
import json

# Writing Python data to a JSON file
person = {'name': 'Anna', 'age': 25}
with open('person.json', 'w') as f:
    json.dump(person, f, indent=2)
This reads JSON, updates it, then writes it back to a new file.
Python
import json

# Reading and writing JSON in one program
with open('input.json', 'r') as f:
    data = json.load(f)

# Change data
data['new_key'] = 'new value'

with open('output.json', 'w') as f:
    json.dump(data, f, indent=4)
Sample Program

This program saves a user dictionary to a JSON file, then reads it back and prints it.

Python
import json

# Sample data to save
user = {
    'username': 'johndoe',
    'active': True,
    'score': 42
}

# Write data to JSON file
with open('user.json', 'w') as file:
    json.dump(user, file, indent=2)

# Read data back from JSON file
with open('user.json', 'r') as file:
    loaded_user = json.load(file)

print('Loaded user data:')
print(loaded_user)
OutputSuccess
Important Notes

JSON files store data as text, so they are easy to share and read.

Python converts JSON objects to dictionaries and JSON arrays to lists.

Always close files or use with to handle files safely.

Summary

JSON files help save and load data in a simple text format.

Use json.load() to read JSON from files and json.dump() to write Python data to JSON files.

Working with JSON files makes programs share and keep data easily.