72

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?

SL5net
  • 2,282
  • 4
  • 28
  • 44
ThePhi
  • 2,373
  • 3
  • 28
  • 38
  • 1
    If you're comparing serialized JSON values exactly, what will you do about the ordering of object keys? – Josh Lee Sep 14 '17 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. – Martijn Pieters Sep 14 '17 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. – skirtle Sep 14 '17 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). – ThePhi Sep 14 '17 at 20:58

1 Answers1

109

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=(',', ':'))
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • 2
    It may work for simple arrays only. Arrays with objects inside still produce different checksums, so they differ (they have extra chars). – Marek Marczak May 13 '21 at 05:48
  • 1
    To make it indent one can use the indent = indent_size parameter – Ayan Jun 01 '22 at 15:58