Sunday, May 10, 2026
HomeLanguagesHow To Convert Python Dictionary To JSON?

How To Convert Python Dictionary To JSON?

JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.
Note: For more information, refer to Read, Write and Parse JSON using Python
 

Function Used:  

  • json.dumps() 
     
  • json.dump() 
     

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 
     

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 1:

Python3




import json 
      
# Data to be written 
dictionary ={ 
  "id": "04", 
  "name": "sunil", 
  "department": "HR"
} 
      
# Serializing json  
json_object = json.dumps(dictionary, indent = 4) 
print(json_object)


Output

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

Output:

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

Example 2:

Python3




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-1

RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS