This tutorial explains how to read and write json files in Python with examples
How to write to JSOn file in Python
It is easy and simple to write a file in Python.
Python has an json
inbuilt module, first import into code
import json
Next, Define the json object as a dictionary array, Array of objects is defined.
employee = [
{
"id": 1,
"name": "John",
},
{
"id": 2,
"name": "Eric",
},
]
Next, Create a File and open the File.
with open("test.json", "w") as filehandler:
open
function open test.json
file option w
allows you to open the file for write
access.
It returns the file handler.
json.dump()
method writes the json object into a file. It writes the same format into json file.
json.dump only works in Python 2.
You can use json dumps method in python2 and python3 Here is an example
import json
employee = [
{
"id": 1,
"name": "John",
},
{
"id": 2,
"name": "Eric",
},
]
with open("test.json", "w") as filehandler:
json.dump(employee, filehandler) or
json.dumps(employee, filehandler)
``
How do you format the json content and write it into a file?
you want to add `indentation` to json content into a file.
use indent=4 allows you to add 4 spaces for json content
```bash
json.dump(employee, filehandler,indent=4)
How do you sort keys of the json content and write to the file?
Supply the sort_keys=True
parameter to json dumps method
json.dump(employee, filehandler,sort_keys=True)
How do you write json to file using encoding?
- Open the file with
encoding='utf-8'
. - Supply
ensure_ascii=False
parameter to json.dumps method
Here is an example
import json
with open('test.json', 'w', encoding='utf-8') as filehandler:
json.dump(employee, filehandler, ensure_ascii=False, indent=4)
How to read data from JSOn file in Python
This example reads the json data from a file in Python.
Following are steps
- Import JSON module into code
- Open json file in read mode using the open function
- read json file content into variables using json.load() method
- Finally, close the filehandle
import json
filehandle = open( "test.json" , "rb" )
jsonData = json.load(filehandle)
filehandle.close()