简体   繁体   中英

Is there a way to use something equivalent to json.dumps in javascript

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?

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.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM