Skip to main content

Read and Write JSON to File in Python

In our previous Python tutorial, you have learned how to convert string data into JSON in Python. In this tutorial, you will learn how to Read and Write JSON data to a File in Python.

JSON (JavaScript Object Notation) data is an easy-to-read, flexible text-based format that can save and communicate information to other apps. Python has build-in JSON module that accept a JSON string and convert into a dictionary.

Pyhton has open() method to open file and return its object. So let’s proceed to write json data to a file and read json data from a file.

Write JSON Data to a File

We can use with() method with open() method to create a new file and write content into this file. We will convert dictionary data to json object using json.dumps() and write to file using write() method.

The below example code will create a new file employee.json and write json data into it.

#write.py

import json
  
empData = {
  "empid": 1,
  "name": "Jhon William",
  "age": 25,
  "address": "Newyork"
}
  
empObject = json.dumps(empData, indent = 4)
  
with open("employee.json", "w") as outFile:
    outFile.write(empObject)

Read JSON Data from File

We can also read the file using with() method to open a file and then load json file object using json.load() method.

The below example code will read json file employee.json and print file content and it’s type.

#read.py

import json

with open('employee.json', 'r') as openFile:
  
    empObject = json.load(openFile)
  
print(empObject)
print(type(empObject))

Output:

{'empid': 1, 'name': 'Jhon William', 'age': 25, 'address': 'Newyork'}
<class 'dict'>