javascript json不显示所有条目

时间:2012-07-17 15:47:00

标签: javascript jquery json

我有一个非常基本的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]或类似的东西来引用它们。

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

由于

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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": ""
    }
}
]
}