Use json.dumps() or json.dump() function to convert Dictionary to JSON String in Python. dumps method defines the number of units for indentation and where dump has a pointer of the file opened in write or append mode.
json.dumps(dict, indent)
json.dump(dict, file_pointer)
The JSON data is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.
Convert Python Dictionary to JSON String example
Simple example code.
import json
# Data to be written
dictionary = {
"id": "101",
"name": "John",
"department": "IT"
}
# Serializing json
json_object = json.dumps(dictionary, indent=4)
print(json_object)
print(type(json_object))
with open("data.json", "w") as outfile:
json.dump(dictionary, outfile)
Output:
Difference Between Dictionary and JSON
Dictionary | JSON |
Keys can be any hashable object | Keys can be only strings |
Keys cannot be repeated | Keys can be ordered and repeated |
No such default value is set | Keys have a default value of undefined |
Values can be accessed by subscript | Values can be accessed by using “.”(dot) or “[]” |
Can use a single or double quote for the string object | The double quotation is necessary for the string object |
Returns ‘dict’ object type | Return ‘string’ object type |
Difference between dump() and dumps()
dump() | dumps() |
---|---|
The dump() method is used when the Python objects have to be stored in a file. | The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc. |
The dump() needs the json file name in which the output has to be stored as an argument. | The dumps() does not require any such file name to be passed. |
This method writes in the memory and then the command for writing to disk is executed separately | This method directly writes to the json file |
Faster method | 2 times slower |
Do comment if you have any doubts or suggestions on this Python JSON topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.