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

Rajat Vij picture Rajat Vij · Apr 6, 2017 · Viewed 8k times · Source

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?

Answer

Ouroborus picture Ouroborus · Apr 6, 2017

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