Reading and Writing JSON to a File in Python

In this tutorial, we are going to learn how to read and write JSON to a file in Python using the built-in Python module. We will store our data in the dict object and store it in the file as a serialized JSON string. Let’s do it.

Writing JSON in the file

Python provides a built-in module json to handle JSON related tasks. Refer to the code below to understand how we are using the dict object to create a JSON object and then storing it in the file.

import json

data = {}
data['users'] = []
data['users'].append({
    'name': 'John',
    'website': 'codeforgeek.com',
    'from': 'Nebraska'
})
data['users'].append({
    'name': 'Mary',
    'website': 'apple.com',
    'from': 'Texas'
})
data['users'].append({
    'name': 'Robert',
    'website': 'amazon.com',
    'from': 'New york'
})

with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)

first, we import the json library, then we construct some sample data to write to our file. We used the generic user’s data to store it in our file.

After we are done building the JSON object, we use the with statement to open our destination file, then use json.dump method to write the data object to the outfile file in the form of a JSON string.

Let’s learn how to read the JSON from a file.

Reading JSON from a File

We can use the same json python module to read the content from a file. Let’s check the example in the code directly.

import json

with open('data.txt') as json_file:
    data = json.load(json_file)
    for u in data['users']:
        print('Name: ' + u['name'])
        print('Website: ' + u['website'])
        print('From: ' + u['from'])
        print('')

we use the json.load method to read the string from the file, parse the JSON data, populates a Python dict object with the data. Once we have the data in the object, we can iterate through it using any loop, in our case we are using the for loop.

This is the most simpler way to read and write JSON objects in the file. Let us know how you handle the JSON in Python.

Pankaj Kumar
Pankaj Kumar
Articles: 208