如何在jsp中创建json对象?
var jsonObj = {
"firstname": "test",
"lastName": "test",
"email": "test",
"mobile": "test",
"place": "test",
"country": "test"
};
alert(jsonObj.length);
这会打印“未定义”的长度。
var json = {"person":
{
"p1":
{"home":
{"address":0,
"phoneNumber":0
},
"office":
{"address":0,
"phoneNumber":0
}
},
"p2":
{"home":
{"address":0,
"phoneNumber":0
},
"office":
{"address":0,
"phoneNumber":0
}
},
"p3":
{"home":
{"address":0,
"phoneNumber":0
},
"office":
{"address":0,
"phoneNumber":0
}
},
},
"msg":"People data"
} ;
假设这是我的json对象。 我想运行循环并遍历值..
alert("json length = " + Object.keys( json ).length); //2
alert("keys in json : " + Object.keys(json)); //person,msg
var people = json.person;
var personLen = Object.keys( people ).length; //3
现在我想运行一个循环并获取p1,p2,p3 ..
中的值for(i=0; i<people; i++) {
var person = people[i]; //but this doesnt work
}
如何使用循环获取这些值?
答案 0 :(得分:2)
这打印&#34; undefined&#34;长度。
因为它没有名为length
的属性,并且它不是具有内置属性length
的数组。
如果要获取此对象中的属性数,请尝试
Object.keys( jsonObj ).length
答案 1 :(得分:1)
对象
上没有长度属性var jsonObj = {
"firstname": "test",
"lastName": "test",
"email": "test",
"mobile": "test",
"place": "test",
"country": "test"
};
// It will return an array of 6 elements['test','test','test','test','test','test']
var a =Object.keys(jsonObj)
alert(a.length);