In writing a django app, I am returning the following json on a jQuery ajax call:
{
"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 the javascript/jQuery callback function, I can access the is_owner, author, etc. easily enough.
is_owner = json.is_owner;
author = json.author;
But for meanings, the numbers are different depending on what it pulls from the server. On the server side for the meanings part, right now what I'm doing is constructing a dictionary like so:
meanings_dict = {}
meanings = requested_tayke.meanings.all()
for meaning in meanings:
meanings_dict[meaning.location] = meaning.text
and then returning a 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 do I access the 'meanings' data from my json in javascript? I need to loop through all of it. Maybe I need to be loading it into json differently. I have full control so of both the server and client side so I'm willing to change either to make it work. Also worth noting: I'm not using Django's serialize functionality. I couldn't make it work with my situation.
it works (roughly) like how a dict works in python: you can iterate over the keys in a json object.
var meanings = json.meanings;
for (var key in meanings )
var value = meanings[key];
it might break if you use a naughty library that adds elements to object's prototype, so for defensive purposes, the established good practice is to write
for(var key in meanings)
if (meanings.hasOwnProperty(key))
var value = meanings[key];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With