Mona Coder Mona Coder - 5 months ago 12
jQuery Question

Not Able to Access Data in a Complex JSON Format

Can you please take a look at this snippet and let me know why I am not able to access to data in

detail
option of the JSON? what I would like to do is loading the
firstName
,
lastName
, and
age
into the list for each object.



var data = {
"events": [{
"date": "one",
"event": "",
"info": "Copenhagen",
"detail": [{
"firstName": "Sally",
"lastName": "Green",
"age": 27
}]
}, {
"date": "two",
"event": "",
"info": "Copenhagen",
"detail": [{
"firstName": "Sally",
"lastName": "Green",
"age": 27
}]
}, {
"date": "three",
"event": "",
"info": "Copenhagen",
"detail": [{
"firstName": "Sally",
"lastName": "Green",
"age": 27
}]
}]
};
for (p = 0; p < data.events.length; p++) {
$("p").append(data.events[p].date);
for (i = 0; i < data.events.detail.length; i++) {
$("ul").append('<li>'+data.events.detail[i]+'</li>');

}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<p></p>
<ul></ul>
</div>




Answer

Firstly, what you have written isn't technically "JSON", it's just a JavaScript object. However, you're on the right path. It's not exactly clear what you're asking for but I've expanded on what you have to give you something that will hopefully be helpful regardless.

var data = {
    "events": [
        {
            "date": "one",
            "event": "",
            "info": "Copenhagen",
            "detail": [
                {
                    "firstName": "Sally",
                    "lastName": "Green",
                    "age": 27
                }
            ]
        }, 
        {
            "date": "two",
            "event": "",
            "info": "Copenhagen",
            "detail": [
                {
                    "firstName": "John",
                    "lastName": "Blue",
                    "age": 22
                }
            ]
        }, 
        {
            "date": "three",
            "event": "",
            "info": "Copenhagen",
            "detail": [
                {
                    "firstName": "Sam",
                    "lastName": "Red",
                    "age": 25
                }
            ]
        }
    ]
};
for (i = 0; i < data.events.length; i++) {
    $(".container").append('<p>' + data.events[i].date + '</p>');
    for (j = 0; j < data.events[i].detail.length; j++) {
        $(".container").append('<ul></ul>');
        $(".container ul:last").append('<li>' + data.events[i].detail[j].firstName + '</li>');
        $(".container ul:last").append('<li>' + data.events[i].detail[j].lastName + '</li>');
        $(".container ul:last").append('<li>' + data.events[i].detail[j].age+ '</li>');
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
</div>