-6

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

2
  • 1
    There are probably dozens of questions just like this one on SO every day. Do some research and try something FCOL Commented Jan 30, 2014 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 Commented Jan 30, 2014 at 17:26

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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
0
for (var i=0; i<questions.length; i++) {
    var choices = questions[i].choices;
    console.log(choices.a);
    console.log(choices.b);
}

1 Comment

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

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.