Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an array in a JSON object?

Tags:

I have the following JSON object:

[
    {
        "comments": [
            {
                "created_at": "2011-02-09T14:42:42-08:00",
                "thumb": "xxxxxxx",
                "level": 1,
                "id": 214,
                "user_id": 41,
                "parent_id": 213,
                "content": "<p>xxxxxx</p>",
                "full_name": "xx K"
            },
            {
                "created_at": "2011-02-09T14:41:23-08:00",
                "thumb": "xxxxxxxxxxxxx",
                "level": 0,
                "id": 213,
                "user_id": 19,
                "parent_id": null,
                "content": "<p>this is another test</p>",
                "full_name": "asd asd asd asd asd"
            }
        ],
        "eee1": "asdadsdas",
        "eee2": "bbbbb"
    }
]

This is coming from a $.ajax request, in success I have....

success: function (dataJS) {
    console.log(dataJS);
    console.log(dataJS[eee1]);
    console.log(dataJS.comments);
}

Problem is I can't get access to the items in the JSON object, even though dataJS does show correctly in the console. Ideas?

like image 548
AnApprentice Avatar asked Mar 02 '11 21:03

AnApprentice


People also ask

How do you access an array inside a JSON object?

You can access the array values by using the index number: x = myObj. rights[0]; Program output.

How do you access elements in a JSON object?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

Can you use array in JSON?

Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

How do you access an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };


2 Answers

That's because your base object is an array as well.

console.log(dataJS[0].comments[0]);

I suspect that would work

like image 127
Darko Z Avatar answered Oct 14 '22 17:10

Darko Z


the JSON you have coming back is actually an array itself, so...

dataJS[0].comments[0].created_at

will be 2011-02-09T14:42:42-08:00, etc...

Both dataJS and comments are arrays, and need indexes to access the appropriate elements.

like image 33
jondavidjohn Avatar answered Oct 14 '22 16:10

jondavidjohn