ciprian ciprian - 2 years ago 134
jQuery Question

Get array from json

I m trying to access

chats
from the JSON below.

{"count":41,"count_id":5,"pic":null,"chats":[{"id":13,"user_id":1,"yiinput_id":5,"chat":"i like to say hello"},{"id":14,"user_id":1,"yiinput_id":5,"chat":"another chat here"}]}


Tried like this:

console.log( data );
console.log( data[chats] );
console.log(data[0].chats);
console.log(data[0].chats[0]);

Answer Source

If it's an object then you can get the value by using data.chats, in case it's string then you need to parse the json string using JSON.parse() to convert it to object.

var json = '{"count":41,"count_id":5,"pic":null,"chats":[{"id":13,"user_id":1,"yiinput_id":5,"chat":"i like to say hello"},{"id":14,"user_id":1,"yiinput_id":5,"chat":"another chat here"}]}';

var obj = JSON.parse(json);

console.log(obj.chats);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download