QuizCure
Find Available Solution Here!

Save Dictionary as Json file python

Deepak Apr 21, 2024

To handle tasks involving JSON, it is necessary to import Python's built-in module for JSON. With code examples, we will learn how to utilize the JSON dump and dumps methods in Python to save a dictionary as JSON and what the differences between them are.

How to Save Dictionary as Json Python

Before moving on to explore how to save dictionary as JSON python, let's first understand the method for saving data in a JSON file

json.dump(dictionary, fp)
Arguments:
dictionary – supply the dictionary parameter to be transformed into a JSON object
fp: fp stands for file descriptor, which is the file pointer used for writing or appending.

JSON dump method is mostly used to convert Python data to a JSON file using a conversion table, such as the dictionary data in the present example.

Code Snippet example

import json

dict = {}

dict ["employee"] = {
"name": "Peter",
"department": "HR"
}
dict ["department"] = {
"name": "HR"

}

#create JSON file in python 
with open('test.json', 'w') as fp:
    json.dump(dict, fp)

    

Explanation: In this case, the conversion table is used by the json.dump method to serialize the object into a JSON-formatted stream.

Once run, it will write Python data to a file-like object. So let's look at the contents of the test.json JSON file. It will look like this:

{"employee": {"name": "Peter", "department": "HR"}, "department": {"name": "HR"}}

In the previous example we saw how to convert a dictionary to JSON. Now Let’s rewrite the same code using the one line of code, we may rebuild the first two lines of the dump method execution as below

json.dump(dict, open('testagain.json', 'w'))

The sample above uses a file pointer and a dict as its two main inputs. The dump method also supports other additional useful arguments, including

  • sort_keys: Sorting keys alphabetically with sort keys (if not passed it will be false)
  • Indent: Data is indented using N spaces when it is indented. (None by default)

And more.

As a result, we can add extra arguments to it as necessary and appropriate in our code.

How may a Python object be converted to string format?

Python data can be converted to string JSON format by using the json.dumps method. dumps method Serialize an object using the conversion table below to a JSON-formatted string.

Conversion table

Python JSON
intNumber
float Number
dict Object
tuple array
list array
str string

We will discuss the json.dumps function since we are talking about how to save a dictionary to a JSON file here.
Lets get started

import json

dict = {}

dict ["employee"] = {
"name": "Peter",
"department": "HR"
}
dict ["department"] = {
"name": "HR"

}
s = json.dumps(dict)
print(type(s))
open("output.json","w").write(s)

Explanation: Here, the built-in open method is utilized to open a file in writing mode, and json.dumps return a string in JSON format for the provided dict. The w write mode overwrites the contents of the given file. If we wish to append file content, we can pass a

The return type of json.dumps is a string as we can see from print(type(s)) output.

Thus, the output of the file output.json will be as follows.

{"employee": {"name": "Peter", "department": "HR"}, "department": {"name": "HR"}}

In these circumstances, we can use the JSON inbuilt method dumps to write a JSON file.

How to fix the AttributeError: Partially initialized module 'json' has no attribute 'dump' (possibly as a result of a circular import) error?

When you face a circular import issue, you should first verify whether the file name matches the name of the imported module or not.

This typically happens when we import a module that has the same name as a file. Let's understand the following code example.

#filename: json.py


import json

#created dictionary for demo

dict = {}

dict ["employee"] = {
"name": "Peter",
"department": "HR"
}

json.dump(dict, open('result.json', 'w'))

Result:

AttributeError: partially initialized module 'json' has no attribute 'dump' (most likely due to a circular import)

Explanation: An error was generated because we imported the same module, JSON, and used the same file name, json.py.

Was this post helpful?

Send Feedback

Connect With QuizCure


Follow Us and Stay tuned with upcoming blog posts and updates.

Contributed By

Deepak

Deepak

QC STAFF
51 Posts
  • PHP
  • JAVA
  • PYTHON
  • MYSQL
  • SEO

You May Like to Read

Scroll up