15

I am supplying a list of objects to my django template. I have a conditions where i am accessing one of the field of object in template which is a json field containing u' characters like {u'option': False, u'name': u'test string'}

We usually use json.dumps for this in python to convert this to {"option": False, "name": "test string"}, which is proper json that i want to have as i need to access such string in my javascript.

Is there a simple way to do this in javascript? I would like to avoid using regex to strip out u' and ' and replace with "

Sorry if this was very basic. Don't know much about javascript.

Or is there a way to just encode my object fields to_json somehow from python?

Rajat Vij
  • 317
  • 2
  • 6
  • 16

2 Answers2

17

The equivalent to Python's json.dumps() in JavaScript is JSON.stringify() as in:

var jsonstr = JSON.stringify(someVariable);

Valid JSON doesn't contain structures like u'something', only "something". If you really have a string like that, it's likely from Python via repr() or similar.

If you're trying to convert Python objects to JavaScript objects from within their respective environments, in Python you would convert them to a JSON encoded strings using json.dumps(), transfer the strings to the JavaScript environment, and then use JSON.parse() to convert them back into objects.

(Keep in mind that JSON doesn't understand anything beyond some basic types such as string, float, boolean, array, and key:value structures. For example, trying to transfer a Python datetime object is likely to get you string or a collection key:value pairs rather than an actual JavaScript Date object.)

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
  • Thanks for the answer. But i just went with updating what i was serving from django. It was cleaner and easier to do. as JSON.stringify wasn't removing `u'` from Json fields. So had to handle that in python anyways. – Rajat Vij Apr 06 '17 at 20:03
  • Warning on an array/list, they are not equivalent. I found this discrepancy with the prettyprinting by python on a list. (Python adds some space by default when Javascript doesn't) – ThePhi Sep 14 '17 at 20:47
3

The difference is that json.dumps applies some minor pretty-printing by default but JSON.stringify does not, you can see below for same.
  Python:

 >>> import json
 >>> json.dumps({"candidate" : 5, "data": 1})
     '{"candidate": 5, "data": 1}'

  Javacript:

 > JSON.stringify({"candidate" : 5, "data": 1})
   '{"candidate":5,"data":1}'

But with some modification, we can have the same JSON string, and to verify both are the same JSON string in formatting as well, we can generate the hash for both JSON strings and compare. There are two ways for it:-
  1. Modifying javascript JSON string to make it equivalent to a python JSON string.
    Python:
    >>> import json,hashlib
    >>> a = json.dumps({"candidate" : 5, "data": 1}, sort_keys=True)
    >>> hashlib.md5(a.encode("utf-8")).hexdigest()
        '12db79ee4a76db2f4fc48624140adc7e'
    
    Javacript:
    > const Crypto = require("crypto-js")
      undefined
    > const a = JSON.stringify({"candidate" : 5, "data": 1}).replaceAll(":", ": ").replaceAll(",", ", ")
      undefined
    > Crypto.MD5(a).toString(Crypto.enc.Hex)
      '12db79ee4a76db2f4fc48624140adc7e'
    
  2. Modifying python JSON string to make it equivalent to a javascript JSON string.
    Python:
    >>> import json,hashlib
    >>> a = json.dumps({"candidate" : 5, "data": 1}, separators=(',', ':'))
    >>> hashlib.md5(a.encode("utf-8")).hexdigest()
        '92e99f0a99ad2a3b5e02f717a2fb83c2'
    
    Javacript:
    > const Crypto = require("crypto-js")
      undefined
    > const a = JSON.stringify({"candidate" : 5, "data": 1})
      undefined
    > Crypto.MD5(a).toString(Crypto.enc.Hex)
      '92e99f0a99ad2a3b5e02f717a2fb83c2'
    

    Note:- To run javascript code, crypto-js npm pkg should be installed as same location where you started the node shell.

Piyush Kumar
  • 169
  • 1
  • 9