Python

How to Save Dict as Json in Python : Solutions

To save dict as json python, we can use dump() and dumps() functions. If you want to create a JSON object then use dumps() function. On the opposite side, if you want to create a JSON File then you need to invoke dump() function. There are some differences in the supportive parameters for this function. In this article, we will explore both these functions with an example.

How to save dict as json python : (Methods ) –

As I explained the first method is using dumps() function. So let’s start.

  1. Using JSON dumps() –

Let’s create a sample dict object and then we will create a JSON object out of it.

import json
sample_dict ={ 
  "key1": 1, 
  "key2": 2, 
  "key3": 3
} 
json_obj = json.dumps(sample_dict, indent = 3) 
print(json_obj)

Here we need to first import json module and for this, we need not install any library. Because this json module comes default with Python.

Also while invoking this dumps() method we are also passing a parameter indent, it is for indentation.

save dict as json python using dumps

2 . Using JSON dump() –

If we want to create a JSON type file from dict python object then we will use this dump(). To explain let’s take the above sample dict and write in some JSON file. Here is the code.

import json
sample_dict ={ 
  "key1": 1, 
  "key2": 2, 
  "key3": 3
} 
with open("sample_file.json", "w") as file:
    json.dump(sample_dict, file)

Here we will use sample_file file name to write the dict into json file. Now let’s execute and check the output.

save dict as json file

 

JSON File is very useful in storing serializable data formats. Typically we use it in configuring application, Transferring data from one server to another server, and so on. It is too compatible with python dict ( dictionary ) object and NO-SQL databases as both maintain key-value pair data type. It is very specific in code configuration.

Please read a more detailed article on a similar topic :

How to Convert python dict to json ? Step by Step Implementation

 

Thanks

Data Science Learner Team