Quoting via python-dictionary-turn-in-json in javascript

When writing a django application, I return the following json to call jQuery ajax:

{ "is_owner": "T", "author": "me", "overall": "the surfing lifestyle", "score": "1", "meanings": { "0": "something", "1": "something else", "3": "yet something else", "23": "something random" }, "user vote": "1" } 

In javascript / jQuery callback function, I can easily access is_owner, author, etc.

 is_owner = json.is_owner; author = json.author; 

But for the numbers, the numbers differ depending on what they pull from the server. On the server side, for part of the values, right now, what I'm doing is creating a dictionary like this:

 meanings_dict = {} meanings = requested_tayke.meanings.all() for meaning in meanings: meanings_dict[meaning.location] = meaning.text 

and then returning json, I create like this:

 test_json = simplejson.dumps({'is_owner':is_owner, 'overall':overall, 'score':str(score),'user vote':str(user_vote), 'author': author, 'meanings' : meanings_dict }) print test_json return HttpResponse(test_json) 

My question is this: how can I access the "value" data from my json in javascript? I need to miss it all. Maybe I need to load it differently in json. I have full control over the server and the client side, so I'm ready to change either to make it work. Also worth noting: I do not use Django serialization functionality. I could not get him to work with my situation.

+4
source share
1 answer

it works (roughly), like the way dict works in python: you can iterate over keys in a json object.

 var meanings = json.meanings; for (var key in meanings ) var value = meanings[key]; 

it can break if you use a naughty library that adds elements to the prototype of an object, so for defensive purposes, itโ€™s good practice to write

 for(var key in meanings) if (meanings.hasOwnProperty(key)) var value = meanings[key]; 
+11
source

Source: https://habr.com/ru/post/1304217/


All Articles