Python JSON Stringify
-
Difference Between the JavaScript
JSON.stringify()
Function and Pythonjson.dumps()
Function -
Use the Python
json.dumps()
Function Similar to the JavaScriptJSON.stringify()
Function

This tutorial will tackle the methods to make Python’s json.dumps()
function work like the JSON.stringify()
function of JavaScript.
Difference Between the JavaScript JSON.stringify()
Function and Python json.dumps()
Function
Whenever we use the JSON.stringify()
function in JavaScript on an array, the white spaces between the elements are removed by default. The following code example shows a working implementation of this function in JavaScript.
Code:
var arr = [7, 8, 6];
JSON.stringify(arr)
Output:
[7,8,6]
We initialized an array and passed it to the JSON.stringify()
function in the above code. The output shows that the function removed all the white spaces between the array elements.
Whereas in Python, the equivalent function is json.dumps()
which does not remove these white spaces by default. A working implementation of this function is given in the coding example below.
Code:
import json
arr = [7, 8, 6]
json.dumps(arr)
Output:
[7, 8, 6]
We initialized a list and passed it to the json.dumps()
function in the above code. The output shows that the function keeps one white space between all the list elements.
Use the Python json.dumps()
Function Similar to the JavaScript JSON.stringify()
Function
We can remove the white spaces from the output of the json.dumps()
function by specifying separators with the separators
parameter. The following code snippet shows a working demonstration of this approach in Python.
Code:
import json
arr = [7, 8, 6]
json.dumps(arr, separators=(',', ':'))
Output:
[7,8,6]
We specified the separators=(',',':')
to remove the white spaces between the list elements. The output shows that the white spaces between the list elements have been removed.
Now, this json.dumps()
function in Python works exactly like the JSON.stringify()
function in JavaScript.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedInRelated Article - Python JSON
- Get JSON From URL in Python
- Pretty Print a JSON File in Python
- Append Data to a JSON File Using Python
- Flatten JSON in Python
- Python Compare Multilevel JSON Objects Using JSON Diff
- Serialize a Python Class Object to JSON