2

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

0

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

5 Comments

Hello thank you for your help so far, doing the first recommendation of item.stuff[0].content I get Uncaught TypeError: Cannot read property '0' of undefined .... and for the second one I get Uncaught ReferenceError: stuff is not defined
@user3709532 can you provide jsfiddle ?
@user3709532 I delete my answer and we use Anik's one to solve the problem
@user3709532 i have created a fiddle this might help you : jsfiddle.net/aiubian/knner7en/1
thank you @AnikIslamAbhi that works, I forgot to change "stuff" to "item" when doing the console.log command... Thanks!
2

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.

Comments

2

You json data is not an array. so you don't need to use each. But stuff is an array so take it's specific index or loop through it.

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

         //or loop through like 
         //$.each(data.stuff,function(i,item){
         //   console.log(item.content);
         //});     
    });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.