Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  30] [ 7]  / answers: 1 / hits: 22091  / 7 Years ago, thu, april 6, 2017, 12:00:00

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?


More From » python

 Answers
308

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


[#58244] Tuesday, April 4, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;