0

我有一个非常基本的 json 文件,我正在使用 jquery / javascript 加载它。现在我只是想提醒我的一些数据。我遇到的问题是我的 JSON 文件中有 3 个主要项目(称为“类别”),但由于某种原因,您只能阅读最后一个。

我的 JSON 文件如下所示:

{
"category":{
    "name":"Caribbean Travel",
    "article":{
        "id": "1",
        "title": "",
        "teaser": "",
        "image": "",
        "date": "",
        "map": "",
        "body": ""
    }
},
"category":{
    "name":"European Travel",
    "article":{
        "id": "2",
        "title": "",
        "teaser": "",
        "image": "",
        "date": "",
        "map": "",
        "body": ""
    }
},
"category":{
    "name":"U.S. Travel",
    "article":{
        "id": "3",
        "title": "",
        "teaser": "",
        "image": "",
        "date": "",
        "map": "",
        "body": ""
    }
}

}

我调用 json 文件并提醒一些信息,如下所示:

$(document).ready(function(){
$.getJSON("news.json",
    function(data){
        alert(JSON.stringify(data));
        //alert(data.category.article.id);
    });

});

所以当我查看数据时,我看到的只是最后的类别信息(美国旅游)。它根本没有显示前2名。而且我不能使用 data.category[1] 或类似的东西来引用它们。

有谁知道我在这里做错了什么?

谢谢

4

2 回答 2

2

您的 json 文件应如下所示:

[{
    "name": "Caribbean Travel",
    "articles": [{
        "id": "1",
        "title": "",
        "teaser": "",
        "image": "",
        "date": "",
        "map": "",
        "body": ""
    }]
}, {
    "name": "European Travel",
    "articles": [{
        "id": "2",
        "title": "",
        "teaser": "",
        "image": "",
        "date": "",
        "map": "",
        "body": ""
    }]
}, {
    "name": "U.S. Travel",
    "articles": [{
        "id": "3",
        "title": "",
        "teaser": "",
        "image": "",
        "date": "",
        "map": "",
        "body": ""
    }, {
        "id": "4",
        "title": "",
        "teaser": "",
        "image": "",
        "date": "",
        "map": "",
        "body": ""
    }]
}]

data[0]将是第一类,data[1]第二类,依此类推。

alert(data[0].articles[0].id) //alert first category's first article's id
alert(data[2].name) //alert third category's name
alert(data[1].articles[0].body) //alert second category's first article's body
alert(data[2].articles[1].body) //alert third category's second article's body
于 2012-07-17T15:50:16.460 回答
0
{"category":[
{
    "name":"Caribbean Travel",
    "article":{
        "id": "1",
        "title": "",
        "teaser": "",
        "image": "",
        "date": "",
        "map": "",
        "body": ""
    }
},
{
    "name":"European Travel",
    "article":{
        "id": "2",
        "title": "",
        "teaser": "",
        "image": "",
        "date": "",
        "map": "",
        "body": ""
    }
},
{
    "name":"U.S. Travel",
    "article":{
        "id": "3",
        "title": "",
        "teaser": "",
        "image": "",
        "date": "",
        "map": "",
        "body": ""
    }
}
]
}
于 2012-07-17T15:52:47.813 回答