store json to file in python

How to Store JSON to File in Python

JSON is a popular data format used by many applications and services around the world for data exchange and transfer. If your application/website runs on python, you may need to write or save JSON data to file in Python. In this article, we will learn how to store JSON to file in Python. JSON data is similar to a python dictionary. It consists of key-value pairs within {} and quoted strings. We will use python’s inbuilt library json to write and read JSON data.


How to Store JSON to File in Python

Writing, saving or storing JSON to file is known as JSON serialization. In this case, we convert python objects such as dictionary, list, array, etc. into equivalent JSON data. Since most of JSON data types are similar to those in Python, it is easy to convert JSON data into Python object and vice versa. Here is a conversion table of python objects and their equivalent JSON object.

PYTHON OBJECTJSON OBJECT
dictobject
list, tuplearray
strstring
int, long, floatnumbers
Truetrue
Falsefalse

You can use dump() or dumps() method to write JSON data to file. We will look at how to use json.dumps() to write JSON data to file.

Create an empty python file.

$ sudo vi write_json.py

Add the following lines to it, to import json library into your code.

#!/usr/bin/env python

import json

Next, we create a sample Python dictionary object that we will write to a file data.json.

# Data to be written
dictionary ={
    "name" : "john doe",
    "rollno" : 56,
    "cgpa" : 8.6,
    "phonenumber" : "8976775500"
}

Next, we will call json.dumps() function to serialize python data to JSON data. json.dumps() takes two arguments – dictionary to be converted into JSON, and an optional argument to define indent level.

# Serializing json 
json_object = json.dumps(dictionary, indent = 4)
  
# Writing to data.json
with open("data.json", "w") as outfile:
    outfile.write(json_object)

Save and close the file. Run it with the following command.

$ python write_json.py

In this case, we first convert python object into JSON string json_object and then use write() function to write JSON data to file data.json. Then we use write() function to simply write this string into a file data.json.

Here is the complete code for your reference.

#!/usr/bin/env python

import json

# Data to be written
dictionary ={
    "name" : "john doe",
    "rollno" : 56,
    "cgpa" : 8.6,
    "phonenumber" : "8976775500"
}

# Serializing json 
json_object = json.dumps(dictionary, indent = 4)
  
# Writing to data.json
with open("data.json", "w") as out_file:
    out_file.write(json_object)

If you want to directly convert python object to JSON string and write to file, you can also use json.dump() function. It requires two arguments – python dictionary to be converted to JSON string, and file pointer for the file where you want JSON to be written. Here is an example to store JSON to file using json.dump() function.

#!/usr/bin/env python
import json
  
# Data to be written
dictionary ={
    "name" : "john doe",
    "rollno" : 56,
    "cgpa" : 8.6,
    "phonenumber" : "8976775500"
}
  
with open("data.json", "w") as out_file:
    json.dump(dictionary, out_file)

This code is similar to the one using json.dumps() above, except that we use json.dump() to directly convert python dictionary to JSON string and write it to file data.json.

Similarly, python’s json library also provides load() function to read JSON string from file into python object. Here is an example where we use open() function to open JSON file, use json.load() function to load JSON data into python dictionary. Thereafter you can use it as per your requirement.

import json
  
# Opening JSON file
with open('data.json', 'r') as open_file:
  
    # Reading from json file
    json_object = json.load(open_file)
  
print(json_object)

In this article, we have learnt how to store JSON data to file in python. If you want to convert Python dictionary to JSON string only, use json.dumps() function. If you want to convert Python dictionary to JSON object and write it to file, use json.dump() function. We have also learnt how to read data from JSON file and convert it into Python dictionary, using json.load() function.

Also read:

How to Handle Multiple Exceptions in Python
How to Make File Executable in Linux
How to Recursively Change Folder Permission in Linux
How to Get Size of Directory in Linux
How to Calculate Time Difference in Python

Leave a Reply

Your email address will not be published. Required fields are marked *