-6

i have a problem in retrieving json objects. how to retrieve the objects inside the "choices" key object? thanks for your help...

ymtExpo
  • 1
  • 2
  • 1
    There are probably dozens of questions just like this one on SO *every day*. Do some research and try something FCOL – Dexygen Jan 30 '14 at 14:35
  • thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much – ymtExpo Jan 30 '14 at 17:26

3 Answers3

0

Assuming you have a var assigment like var myobj = { ... } where ... is your json object in the post, then you would access all the choices data points like this:

myobj.questions[0].choices.a
myobj.questions[0].choices.b
myobj.questions[1].choices.a
myobj.questions[1].choices.b

Are you asking something more specific about how to loop through all questions and choices?

Update: After your comment, I think you might be looking for something more like this:

for (var qi=0; qi < myobj.questions.length; qi++) {
    var q = myobj.questions[qi];
    console.log(q.ques);
    for (var choiceKey in q.choices) {
        console.log("    " + choiceKey + " --> " + q.choices[choiceKey]);
    }
}

Simply replace the console.log() statements with whatever logic you need. The output of running the above code on your example JSON is this:

how old are you?
    a --> 19
    b --> 20
question two?
    a --> answer1
    b --> answer2
David Fleeman
  • 2,588
  • 14
  • 17
  • thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much – ymtExpo Jan 30 '14 at 17:25
0

Like so (to loop)

for (var i = 0; i < data.questions.length; i++) {
    console.log(data.questions[i].choices.a);
    console.log(data.questions[i].choices.b);
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much – ymtExpo Jan 30 '14 at 17:24
0
for (var i=0; i<questions.length; i++) {
    var choices = questions[i].choices;
    console.log(choices.a);
    console.log(choices.b);
}
Stephen Thomas
  • 13,843
  • 2
  • 32
  • 53
  • thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much – ymtExpo Jan 30 '14 at 17:25