Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify (Javascript) and json.dumps (Python) not equivalent on a list?

In javascript:

var myarray = [2, 3]; var json_myarray = JSON.stringify(myarray) // '[2,3]' 

But in Python:

mylist = [2, 3] json_mylist = json.dumps(mylist) # '[2, 3]' <-- Note the space 

So the 2 functions aren't equivalent. It's a bit unexpected for me and a bit problematic when trying to compare some data for example.

Some explanation about it?

like image 903
ThePhi Avatar asked Sep 14 '17 20:09

ThePhi


People also ask

Can you JSON dump a list Python?

To convert a list to json in Python, use the json. dumps() method. The json. dumps() is a built-in function that takes a list as an argument and returns the json value.

Why JSON Stringify does not work on array?

The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON. stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.

What is the difference between JSON dump and JSON dumps?

json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.


1 Answers

The difference is that json.dumps applies some minor pretty-printing by default but JSON.stringify does not.

To remove all whitespace, like JSON.stringify, you need to specify the separators.

json_mylist = json.dumps(mylist, separators=(',', ':')) 
like image 187
Mike Cluck Avatar answered Sep 28 '22 01:09

Mike Cluck