Vlad
Vlad

Reputation: 1797

How to access nested JSON in JS?

So I have this JSON struture that I have successfully passed into JS:

{
"StepOne": [
    {
        "id": "2",
        "type": "1",
        "description": "How are you feeling?",
        "options": [
            {
                "opt_id": "1",
                "opt_desc": "Good"
            },
            {
                "opt_id": "2",
                "opt_desc": "Perfect"
            },
            .... etc

It goes on until PageFive and the amount of questions vary from 1-4 in each step and the options vary from null to about 10 for each question. I want to use this information to generate a multi step form in Javascript, but I can not figure out how to access the inner data. I can only find "PageOne", "PageTwo" etc. I am using this following code to do that:

$(document).ready(function()
    {       
        $('#show-results').click(function() 
        {
            $.post('json.php', function(data) 
            {
                var pushedData = jQuery.parseJSON(data);


                $.each(pushedData, function(i, serverData)
                {
                    alert(i);
                })
            })
        })
    });

Now I have tried these functions to get to the inner values:

var desc = pushedData.PageOne.description;

var desc = pushedData['PageOne']['Description'];

And inside the each loop I've tried stuff like

var desc = PageOne.description;

var desc = PageOne['description'];

It all comes out as undefined. Is there a way to iterate through each of the questions in each Page the same way I have done to iterate through the pages? And from there rinse and repeat to iterate through the options for each question? If I could access each level I should be all set for generating a poll dynamically which is the ultimate goal here.

I think this code is on to something (found out right after I posted). Not quite working though.

$(document).ready(function()
    {       
        $('#show-results').click(function() 
        {
            $.post('JSAAN.php', function(data) 
            {
                var pushedData = jQuery.parseJSON(data);

                $.each(pushedData, function(i, stepData)
                {
                    $.each(stepData, function(j, questionData)
                    {
                      // Print question here
                           $.each(questionData, function(k, optionData)
                           {
                                // Print option here
                           })

                    })
                })
            })
        })
    });

Upvotes: 1

Views: 2577

Answers (2)

Christoph
Christoph

Reputation: 51191

It needs to be

jsonData.StepOne[0].description

since you have an additional [] array wrapper.

Depending on you structure, just omit the additional [], then you can access all the Object Properties directly, it should look like this:

{
"StepOne":
    {
        properties
    },
"StepTwo":
    {
        properties
    }
}

however, it's okay to have such a structure - now you have to write StepOne[x].prop

"StepOne":[
    {
        properties
    },
    {
        other props
    }],
 "StepTwo":[{...

According to the code you posted, this might be what you want, since you have several questions per step(?).

The simple loop looks like the following:

for (var key in o) {
  if (o.hasOwnProperty(key)) {
    console.log(key + " -> " + o[key]);
  }
}

A nested loop is more complicated though:

function loop(obj) {
    $.each(obj, function(key, val) {
        if($.isPlainObject(val) || $.isArray(val)) {

            console.log(key + " is an Object");
            // object or array -> call recursively
            loop(val);

        } else {
           // plain value
           console.log(key + "->" + val);
        }
    });
}

Take a look at this example.

Upvotes: 2

LetterEh
LetterEh

Reputation: 26696

Aside from the StepOne !== PageOne problem:

StepOne is an array, which holds an object.

That makes no sense to me, seeing as there should probably only be one step in StepOne... ...but that's just me.

So you'd have to go:

jsonData.StepOne[0].description;
jsonData.StepOne[0].options[0].opt_desc;
jsonData.StepOne[0].options[1].opt_desc;

et cetera...

Upvotes: 1

Related Questions