Skip to content
Related Articles

Related Articles

Improve Article

Python – Difference between json.dump() and json.dumps()

  • Last Updated : 06 Mar, 2020

JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json.

Note: For more information, refer to Working With JSON Data in Python

json.dumps()

json.dumps() method can convert a Python object into a JSON string.

Syntax: json.dumps(dict, indent)

Parameters:



  • dictionary – name of dictionary which should be converted to JSON object.
  • indent – defines the number of units for indentation

Example:




# Python program to convert 
# Python to JSON 
     
     
import json 
     
# Data to be written 
dictionary =
  "id": "04"
  "name": "sunil"
  "depatment": "HR"
     
# Serializing json  
json_object = json.dumps(dictionary, indent = 4
print(json_object)

Output:

{
    "depatment": "HR",
    "id": "04",
    "name": "sunil"
}

Python objects and their equivalent conversion to JSON:

PythonJSON Equivalent
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull

json.dump()

json.dump() method can be used for writing to JSON file.

Syntax: json.dump(dict, file_pointer)

Parameters:

  • dictionary – name of dictionary which should be converted to JSON object.
  • file pointer – pointer of the file opened in write or append mode.

Example:




# Python program to write JSON
# to a file
   
   
import json
   
# Data to be written
dictionary ={
    "name" : "sathiyajith",
    "rollno" : 56,
    "cgpa" : 8.6,
    "phonenumber" : "9976770500"
}
   
with open("sample.json", "w") as outfile:
    json.dump(dictionary, outfile)

Output:

python-json-write-to-file

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :