79

In javascript:

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

But in Python:

import json 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?

4
  • 1
    If you're comparing serialized JSON values exactly, what will you do about the ordering of object keys? Commented Sep 14, 2017 at 20:42
  • 2
    JSON allows for whitespace between elements; the Python default configuration is to include that whitespace. What is your actual goal here, to compare the JSON value or the exact bytes that are generated by etiher? If the latter, you'll have more issues, like the order of key-value pairs in JSON objects not being set. Commented Sep 14, 2017 at 20:44
  • 1
    The outputs are equivalent, just not the same. JSON has some flexibility when it comes to encoding the same data, it doesn't mandate a canonical form. Whitespace is one example, the use of \u escaping in strings is another. Commented Sep 14, 2017 at 20:47
  • Granted, I can convert the json string to object like a list and doing the comparison. but I found it more direct to compare directly that. The JSON string is in a database, representing a field for a ForeignKey (Django framework) that I'm searching. (And the ordering is important). Commented Sep 14, 2017 at 20:58

1 Answer 1

119

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=(',', ':')) 
Sign up to request clarification or add additional context in comments.

2 Comments

It may work for simple arrays only. Arrays with objects inside still produce different checksums, so they differ (they have extra chars).
To make it indent one can use the indent = indent_size parameter

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.