Skip to content

Python Dictionary to JSON String

  • by

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:

Python Dictionary to JSON String

Difference Between Dictionary and JSON

DictionaryJSON
Keys can be any hashable objectKeys can be only strings
Keys cannot be repeatedKeys can be ordered and repeated
No such default value is setKeys have a default value of undefined
Values can be accessed by subscriptValues can be accessed by using “.”(dot) or “[]”
Can use a single or double quote for the string objectThe double quotation is necessary for the string object
Returns ‘dict’ object typeReturn ‘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 separatelyThis method directly writes to the json file
Faster method2 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.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.