将JSON数据提取到Javascript对象数组中

时间:2015-11-09 16:12:40

标签: javascript jquery json

我有一个带有虚拟文章的JSON文件,用于测试目的。我正在尝试使用jQuery从JSON文件中提取信息,以使用提取的信息创建对象数组。

这是我的JSON文件:

{
    "news": [
        {
            "title": "Test 1",
            "author": "Chicago Tribune",
            "source": "http://www.chicagotribune.com/",
            "preview": "Long-simmering . . .",
            "picture": "IMG" 
        },
        {
            "title": "Test 2",
            "author": "New York Times",
            "source": "http://www.nytimes.com/",
            "preview": "Information . . .",
            "picture": "IMG" 
        },
        {
            "title": "Test 3",
            "author": "Chicago Tribune",
            "source": "http://www.chicagotribune.com/",
            "preview": "Blah blah blah . . .",
            "picture": "IMG" 
        }
    ]
}

这是我的Javascript文件:

// Article array
var articles = [];

// Article 'class'
function Article (title, author, preview, picture) {
    this.title = title;
    this.author = author;
    this.preview = preview;
    this.picture = picture
}

// Pull data from JSON file
$.getJSON('data.json', function(data) {
    $.each(data.news, function (i, j) {
        articles.push(new Article(j.title, j.author, j.preview, j.picture));
    });
});

for (i = 0; i < articles.length; i++) {
    Console.log('Article ' + i + ": " + articles[i].title);
}

articles数组未填满,似乎没有创建任何对象。我的下一步是遍历数组中的每个文件,并使用新填充的文章数组将该数据发布到页面。

1 个答案:

答案 0 :(得分:0)

三件事:

  • 您的JSON无效。您可能会将其粘贴错误,但它应如下所示:

例如:

    {
    "news": [
        {
            "title": "Test 1",
            "author": "Chicago Tribune",
            "source": "http://www.chicagotribune.com/",
            "preview": "Long-simmering . . .",
            "picture": "IMG"
        },
        {
            "title": "Test 2",
            "author": "New York Times",
            "source": "http://www.nytimes.com/",
            "preview": "Information . . .",
            "picture": "IMG"
        },
        {
            "title": "Test 3",
            "author": "Chicago Tribune",
            "source": "http://www.chicagotribune.com/",
            "preview": "Blah blah blah . . .",
            "picture": "IMG"
        },

    ]
};
  • $.each()将循环遍历news数组的每个元素,因此您只能在匿名函数中获得一个元素。试试这个:

例如:

 $.getJSON('data.json', function(data) {
     $.each(data.news, function (i) {
         articles.push(new Article(i.title, i.author, i.preview, i.picture));
     });
 });
  • 您正在遇到异步问题,因为在您的JSON到达之前执行了for循环。如果您的代码取决于for,那么请尝试在$.getJSON来电中添加articles循环。这是异步行为的great explanation

此外,如果您对参数中的内容有任何疑问,请在功能中添加debugger; - 这样您就可以检查并确保您获得所检查的内容。< / p>