Looping through python-dictionary-turned-into-json in javascript.
Posted
by Phil
on Stack Overflow
See other posts from Stack Overflow
or by Phil
Published on 2010-03-16T01:20:59Z
Indexed on
2010/03/16
1:29 UTC
Read the original article
Hit count: 462
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.
© Stack Overflow or respective owner