简体   繁体   English

jQuery:获取JSON错误

[英]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: 我试图从JSON文件中获取某些元素,但我只是无法这样做,我尝试了不同的方法,这是JSON文件:

// 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: 现在我的jQuery代码是:

$(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: 我得到的是一个未捕获的错误类型:

在此输入图像描述

What am I doing wrong? 我究竟做错了什么? Thanks in advance 提前致谢

stuff is an array of object. stuff是一个对象数组。

To access item of an array you have to access it via index 要访问数组的项目,您必须通过index访问它

like this 像这样

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

JSFIDDLE 的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 的jsfiddle

You json data is not an array. 你的json数据不是数组。 so you don't need to use each. 所以你不需要使用每个。 But stuff is an array so take it's specific index or loop through it. stuff是一个数组,所以把它的特定索引或循环通过它。

$(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);
         //});     
    });
});

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. 它正在获取JSON对象的stuff元素,然后是该对的第一个元素,因为这对键“stuff”是一个JSON对象数组。 Then from that last JSON object, its grabbing content. 然后从最后一个JSON对象,它的抓取内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM