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?
You can access the array values by using the index number: x = myObj. rights[0]; Program output.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
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.
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' }] };
That's because your base object is an array as well.
console.log(dataJS[0].comments[0]);
I suspect that would work
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With