Difference Between json.dump() and json.dumps() in Python

In this Python tutorial, we will discuss the difference between json.dump() and json.dumps(). As we know, JSON stands for JavaScript Object Notation. It is a lightweight data format consisting of attribute-value pairs. It is easy to read and write for humans and machines as well. Python provides us with a module named ‘json’ to deal with JSON data. In this post, we will see the difference between the two methods of this module–json.dump() and json.dumps().

json.dump()

This method is used for writing to a JSON file. The syntax for this method is as follows:

json.dump(data, file)

The method takes two parameters. The first parameter is ‘data’ passed as a dictionary which needs to be written to a JSON file. The second parameter is a pointer to the JSON file where the data needs to be stored.

See the below example program.

import json

data = {
    'Name' : 'Lion',
    'Scientific name' : 'Panthera Leo'
}

with open('example.json', 'w') as file:
    json.dump(data, file)

The above program creates a file example.json if there is no existing file with this name and stores the data as the content of the file. Otherwise, it simply stores the data as the content of the JSON file as given below.

{"Name": "Lion", "Scientific name": "Panthera Leo"}

json.dumps()

This method is used for converting a Python object into a JSON string. The syntax for this is as follows:

json.dumps(data, indent)

The first parameter ‘data’ is the data to be converted into JSON string and the second parameter ‘indent’ is the number of unit of indentation. The ‘indent’ parameter is optional.

Have a look at the given example.

import json

data = {
    'Name' : 'Lion',
    'Scientific name' : 'Panthera Leo'
}

json_string = json.dumps(data)
print(json_string)

Output:

{"Name": "Lion", "Scientific name": "Panthera Leo"}

Thank you.

Also read: How to flatten JSON objects in Python

Leave a Reply

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