Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Get JSON error

I'm trying to get certain elements from a JSON file but I'm just not able to do so, I've tried different ways, this is the JSON file:

// data.json
{
    "stuff": [
        {
            "userId": 1,
            "date": "19 Oct 2014",
            "content": "#New Hello on g.co/ABC",
            "entities": {
                "hashtags": ["#New"],
                "urls": ["g.co/ABC"]
            }
        }
    ],
    "user": {
        "avatar": "/assets/avatar.jpg",
        "name": "Daniel"
    }
}

Now my jQuery code is:

$(document).ready(function(){
    $.getJSON('data.json', function(data) {
        //console.log(data);

        $.each(data,function(i,item){
            console.log(item.stuff.content); // I want to print 'content'
        });
    });
});

And all I get is an Uncaught error type:

enter image description here

What am I doing wrong? Thanks in advance

like image 890
user3709532 Avatar asked Apr 27 '26 13:04

user3709532


2 Answers

stuff is an array of object.

To access item of an array you have to access it via index

like this

console.log(data.stuff[0].content);

JSFIDDLE

May be you are iterating an object instead of array of object

If data is an object then try like this

$.each(data.stuff,function(i,item){
    console.log(item.content);
});

JSFIDDLE

like image 198
Anik Islam Abhi Avatar answered Apr 29 '26 02:04

Anik Islam Abhi


This should work:

$.getJSON('data.json', function(data) {
   console.log(data['stuff'][0]['content']);
}

It is getting the stuff element of the JSON object then the first element of that pair, since the pair of key "stuff" is an array of JSON Objects. Then from that last JSON object, its grabbing content.

like image 38
Jonathan Maddox Avatar answered Apr 29 '26 01:04

Jonathan Maddox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!