JSON-检查深度嵌套的JSON中的属性 [英] JSON - Checking for a property in a deeply nested 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
为 not 12,则什么都不做.
I want to loop through each code
AND dateofbirth
and alert if the month
is 12. If the month
is not 12, then do nothing.
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
的值?
How can I loop through dateofbirth
and check for the value of month
?
在代码"下具有多个属性(可以是一个对象)的JSON结构示例.因此,我想遍历code
内的所有属性,并检查month
属性的值,而不是手动检查特定属性.
Example of JSON structure with more than 1 property under 'code' that can be an object. So I want to loop through all the properties within code
and check for the value of the month
property instead of manually checking for a particular property.
{
"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"
}
}
}
]
}
推荐答案
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");
}
}
顺便说一句,您确实应该将生日存储为数字,而不是字符串.
BTW, you really should store birthdates as numbers, not strings.
这篇关于JSON-检查深度嵌套的JSON中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!