实现json迭代

时间:2012-07-26 19:23:18

标签: javascript json

我有以下JSON,需要通过“规则”对象进行迭代。我似乎永远无法正确地称它为能够访问不仅仅是最后一条规则。

如果有人能指出我正确的方向,我会很感激

var rules = [{
"rule":[{
    "fields":["CASE.PROSECUTED_FLAG","CASE.RESTITUTION_SIGNED"],
    "conditions":["N","Y"],
    "actions":"required",
    "action_fields":["test1","test2"]
}],
"rule":[{
    "fields":["CASE.PROSECUTED_FLAG","CASE.RESTITUTION_SIGNED"],
    "conditions":["N","N"],
    "actions": "required",
    "action_fields": ["test3", "test4"]
}],
 "rule":[{
    "fields":["CASE.PROSECUTED_FLAG"],
    "conditions":["Y"],
    "actions": "required",
    "action_fields": ["test5"]
}]
}];




function rulesControl() {
    alert(rules.length);
    for (var rule in rules) {

    var xfields = rules[rule].rule.fields;
    var conditions = rules[rule].rule.conditions;
    var actions = rules[rule].rule.actions;
    var action_fields = rules[rule].rule.action_fields;

    //test the fields (if success, mark them, else clear them)
    if (validateRule(xfields, conditions)) {
        rulesAction(actions, action_fields);
    } else {
        ruleActionMakeClear(action_fields);
    }
    }
}

3 个答案:

答案 0 :(得分:1)

那是因为JSON形成奇怪。它定义了包含对象三次的属性“规则”,实质上是覆盖自身。这可能是你所追求的更多,而不是让所有那些单项数组嵌套在对象中。

var rules = [
{"rule":
    {
    "fields":["CASE.PROSECUTED_FLAG","CASE.RESTITUTION_SIGNED"],
    "conditions":["N","Y"],
    "actions":"required",
    "action_fields":["test1","test2"]
    }
},
{"rule":
    {
    "fields":["CASE.PROSECUTED_FLAG","CASE.RESTITUTION_SIGNED"],
    "conditions":["N","N"],
    "actions": "required",
    "action_fields": ["test3", "test4"]
    }
},
{"rule":
    {
    "fields":["CASE.PROSECUTED_FLAG"],
    "conditions":["Y"],
    "actions": "required",
    "action_fields": ["test5"]
    }
}
];

您可以访问:

rules[i].rule.PROPERTY

其中i是规则的索引值,PROPERTY是字段,条件等

答案 1 :(得分:1)

你错过了curlies ......

var rules = [{"rule":[{}]
      },{  // You are missing this curly braces.
      "rule":[{}]},
      {"rule":[{}]}];

答案 2 :(得分:0)

你只能有一个rule密钥,你只看到最后一条规则的原因是因为规则相互覆盖而最后一条规则是剩下的,我建议使用数组来存储规则。