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

12,954

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

Share:
12,954
Rajat Vij
Author by

Rajat Vij

Updated on June 18, 2022

Comments

  • Rajat Vij
    Rajat Vij almost 2 years

    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?