我需要在循环中解析像{"key1":"val1","key2":"val2","key3":"val3"}
这样的json对象。
尝试:
var inobj = '[{"key1":"val1","key2":"val2","key3":"val3"}]';
var obj = eval(inobj);
for (var i = 0; i < 3; i++) {
var key = i;
var val = obj[key];
alert (key+' = '+val);
}
但我不知道obj.length
。
答案 0 :(得分:5)
var obj = JSON.parse('{"key1":"val1","key2":"val2","key3":"val3"}');
Object.keys(obj).forEach(function (key) {
alert(key + " = " + obj[key]);
});
答案 1 :(得分:1)
你可以统计数据:
Object.keys(obj).length
请参阅堆叠问题:How to efficiently count the number of keys/properties of an object in JavaScript?