用jquery解析json

时间:2011-06-06 21:22:21

标签: jquery json parsing

所以我有一个json对象

var json = {"School":{"Keywords":"HBS","SchoolName":"","SchoolUrl":"/Careers/Apply/University_recruiting/Schools/HBS.aspx"}, "School":{"Keywords":"Stanford","SchoolName":"","SchoolUrl":"/Careers/Apply/University_recruiting/Schools/Stanford.aspx"}}

我想循环查找此对象中的所有关键字。 我试过了$(json.School).each(function(){ console.log(this.Keywords) },但它似乎没有用。有线索吗?

4 个答案:

答案 0 :(得分:1)

您的json对象是嵌套字典数组。用字符串引用其元素,如下所示:

$.each(json['School'], function() {...

答案 1 :(得分:0)

$.each与数组一起使用。你拥有的不是数组。它是一个带有属性的简单javascript对象。以下是javascript中数组的外观:

var json = [
    {
        "Keywords":"HBS",
        "SchoolName":"",
        "SchoolUrl":"/Careers/Apply/University_recruiting/Schools/HBS.aspx"
    }, 
    {
        "Keywords":"Stanford",
        "SchoolName":"",
        "SchoolUrl":"/Careers/Apply/University_recruiting/Schools/Stanford.aspx"
    }
];

现在你可以循环:

$.each(json, function() {
    console.log(this.Keywords);
});

这是一个working live demo

答案 2 :(得分:0)

你应该用于...

for (key in json){
    if (json.hasOwnProperty(key)) {
        alert(json[key]);
    }
}

始终检查属性是否属于对象,以避免从原型继承的属性

编辑 - 这是迭代对象属性的方法,但我不知道你的是否是有效对象

答案 3 :(得分:0)

首先,json是一个可怕的变量名。 JSON存在无效。第一个{应该是[,而最后}应该是]。你应该放弃多余的“学校”财产。

修复:

var schoolArray = [
    {"Keywords":"HBS","SchoolName":"","SchoolUrl":"/Careers/Apply/University_recruiting/Schools/HBS.aspx"},
    {"Keywords":"Stanford","SchoolName":"","SchoolUrl":"/Careers/Apply/University_recruiting/Schools/Stanford.aspx"}];

$.each(schoolArray, function(key, value)
{
    var keywords = value.Keywords;
    var schoolName = value.SchoolName;
});