Python: Read and Write JSON Files

Reading and writing JSON data files in Python is pretty simple. Here I am giving example showing how to read and write JSON data files.

import json

# JSON data file name.
filename = 'sample.json'
# Data to be written in file in JSON format.
data = {
    'department': 'Engineering',
    'employees': [{'id': 1, 'name': 'Employee1'}, {'id': 2, 'name': 'Employee2'}]
}

# Write data to file in JSON format.
with open(filename, 'w') as outfile:
    json.dump(data, outfile)

# Read data from JSON format file.
with open(filename) as infile:
    data = json.load(infile)