JSON - 在深层嵌套的JSON中检查属性

时间:2011-11-14 16:54:48

标签: json

JSON结构:

{
    "codes":[
        {   
                "id":"1",           
                "code":{                
                    "fname":"S",
                    "lname":"K",
                    "dateofbirth":{
                        "month":"12",
                        "day":"02",
                        "year":"1998"
                    }

            }
        },
        {   
                "id":"2",               
                "code":{                
                    "fname":"M",
                    "lname":"D",
                    "dateofbirth":{
                        "month":"10",
                        "day":"02",
                        "year":"1998"
                    }                 
            }
        }
]
}

我想遍历每个code AND dateofbirth,并在month为12时发出提醒。如果month 12,然后什么都不做。

    success: function(data){
        var x;
        for (x = 0; x < data.codes.length; x++){
            var count=0;
            for (property in data.codes[x].code) {
                count++;                                               
            }                   
        }       
    }

如何循环浏览dateofbirth并检查month的值?

在“代码”下可以作为对象的多个属性的JSON结构示例。所以我想遍历code中的所有属性并检查month属性的值,而不是手动检查特定属性。

    {
        "codes":[
            {   
                    "id":"1",           
                    "code":{                
                        "fname":"S",
                        "lname":"K",
                        "dateofbirth":{
                            "month":"12",
                            "day":"02",
                            "year":"1998"
                        },
                        "membership":{
                            "month":"12",
                            "day":"12",
                            "year":"2011"
                        }        
                }
            },
            {   
                    "id":"2",               
                    "code":{                
                        "fname":"M",
                        "lname":"D",
                        "dateofbirth":{
                            "month":"10",
                            "day":"02",
                            "year":"1998"
                        },
                        "membership":{
                            "month":"10",
                            "day":"12",
                            "year":"2011"
                        }                
                }
            }
    ]
    }

1 个答案:

答案 0 :(得分:2)

mycodes=// the object from parsed JSON

for (i=0; i<mycodes.codes.length; i++) {
    if (mycodes.codes[i].code.dateofbirth.month=="12") {
        alert("Code " + mycodes.codes[i].id + " has birth month of 12");
    }
}
顺便说一句,你真的应该把生日存储为数字,而不是字符串。