Write to JSON file and read from a JSON file using Python.

Data Geek
2 min readMar 3, 2021

JSON stands for “JavaScript Object Notification,” which is popularly used for web applications/APIs to communicate.

Write JSON to a file:

Let’s say you have below JSON data that needs to be written to a file.

data = [{
'name': 'Steve',
'Age' : 21 ,
'language': ['English','French' ]
},
{
'name': 'Adam',
'Age' : 23,
'language': ['Spanish','French' ]
} ]

Below is the code to write to the file. If the file is already present, it gets overwritten. Otherwise, a new file gets created with the name mentioned.

import json

with open('testfile.json','w') as f :
json.dump(data,f, indent = 3)

Reading data from a JSON file:

Let’s say you have a JSON file from which you want to read data. Below is the code read data from it.

with open ('testfile.json','r') as f :
data = json.load(f)
print(data)

Output

[{‘name’: ‘Steve’, ‘age’: 21, ‘language’: [‘English’, ‘French’]}, {‘name’: ‘Adam’, ‘age’: 23, ‘language’: [‘Spanish’, ‘French’]}]

Reading JSON data from a text file:

Let’s say you have a data.txt file containing the below.

[
{
"name": "Steve",
"age": 21,
"language": [
"English",
"French"
]
},
]

Below is the code read data from a text file containing JSON data.

import json
with open('data.txt') as json_file:
data = json.load(json_file)
for p in data:
print('Name: ' + p['name'])
print('Age: ' + str(p['age']))

Output

Name: Steve
Age: 21

--

--

Data Geek

I write about Python, Unix, Data Engineering, and Automation Testing.