0

我有下面的 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);
    }
    }
}
4

3 回答 3

1

你缺少卷发...

var rules = [{"rule":[{}]
      },{  // You are missing this curly braces.
      "rule":[{}]},
      {"rule":[{}]}];
于 2012-07-26T19:30:31.853 回答
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 是字段、条件等。

于 2012-07-26T19:29:16.107 回答
0

您只能拥有一个rule键,之所以只看到最后一条规则,是因为规则相互覆盖,最后一个是剩下的,我建议使用数组来存储规则。

于 2012-07-26T19:28:37.273 回答