json dump vs json dumps

Json.dump vs Json.dumps in Python

Python is a popular programming language that provides various modules & packages to work with different data types. It provides JSON module to process JSON data. It contains numerous functions to serve various purposes. It also provides two functions json.dump() and json.dumps(). Although they both look similar, they serve different purposes. In this article, we will look at the difference between json.dump vs json.dumps functions.


Json.dump vs Json.dumps in Python

Here is the key difference between Json.dump and Json.dumps functions in python.


JSON.dumps

JSON.dumps() function converts python object to JSON string. It is useful to return response objects from your website’s backend to its front end.

json.dumps(dict, indent)

In the above function you need to pass the dictionary that you want to convert to JSON string, and the number of units for indentation. The second argument, that is, number of indent, is optional.

Here is an example.

# Python program to convert 
# Python to JSON 
     
     
import json 
     
# Data to be written 
dictionary ={ 
  "id": "43", 
  "name": "sunny"
} 
     
# Serializing json  
json_object = json.dumps(dictionary, indent = 4) 
print(json_object)

You will see the following output.

{ 
  "id": "43", 
  "name": "sunny"
} 


JSON.dump

JSON.dump method is used to write data to JSON file. Here is its syntax.

json.dump(dict, file_pointer)

In the above function, you need to pass the dictionary object and file pointer of the file to which you want to write JSON data.

# Python program to write JSON
# to a file
   
   
import json
   
# Data to be written
dictionary ={
    "name" : "sunny",

    "id":"43"
}
   
with open("sample.json", "w") as outfile:
    json.dump(dictionary, outfile)

If you open the file sample.json it will contain the following data.

{"name" : "sunny","id":"43"}

That’s it. In this article, we have learnt the different between JSON.dump() vs JSON.dumps() function.

Also read:

How to Uninstall Docker in Ubuntu
How to Become Root User in Linux
How to Change Default Home Directory in Linux
How to Remove Sudo Privileges in Linux
How to Install Webmin in CentOS

Leave a Reply

Your email address will not be published.