1

我现在正在学习 json 并让我的壮举变得湿透,可以这么说,我想知道获取包含 json 信息的文件并用它填充网站的最佳方法是什么。该文件将是这样的:

window.test =
{
    "header1":
    [
        { "title": "title1", "author": "author1"},
        { "title": "title2", "author": "author2"},
        { "title": "title3", "author": "author3"}
    ],
    "header2":
    [
        { "title": "title1", "author": "author1"},
        { "title": "title1", "author": "author2"},
        { "title": "title1", "author": "author3"}
    ]
};

那么代码会是这样的吗?

$(function() {
    $.getJSON('jsonFile.js',function(data){
        $.each(data, function(){
            console.log(header1.title);
            console.log(header2.title);
        });
    });
});

同样,我是 JSON 的新手,所以任何教程、建议以及任何能帮助我理解核心概念的东西都会有所帮助。

4

3 回答 3

5

你的json:

{ 
    "header1": 
    [ 
        { "title": "title1", "author": "author1"}, 
        { "title": "title2", "author": "author2"}, 
        { "title": "title3", "author": "author3"} 
    ], 
    "header2": 
    [ 
        { "title": "title1", "author": "author1"}, 
        { "title": "title1", "author": "author2"}, 
        { "title": "title1", "author": "author3"} 
    ] 
}

你的代码:

$(function() {   
    $.getJSON('jsonFile.js',function(data){

        console.log(data.header1[0].title);   
        console.log(data.header2[0].title);     
    });   
});  

(可选)对 data.header1 和 data.header2 执行 each()

于 2012-04-03T20:52:25.043 回答
0

正如其他人所说,您应该删除window.text和结尾的分号。然后当你像这样直接读取文件时,它会被编码为文本,所以你需要在迭代之前将它翻译成 JSON。

您可以var jsonData = JSON.parse(data));从 data 参数中获取 JSON 对象。

于 2012-04-03T20:45:54.780 回答
0

对于您拥有的 JSON 结构,如下所示的循环应该是正确的。

演示

$.each(test, function(key, val) {
    console.log(key); //this will print the header
    $.each(val, function(index, val1) {
        console.log(val1.title + ' ' + val1.author); //this will print the header contents
    });
});
于 2012-04-03T20:46:10.510 回答