1

我需要像{"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

4

2 回答 2

5
var obj = JSON.parse('{"key1":"val1","key2":"val2","key3":"val3"}');

Object.keys(obj).forEach(function (key) {
    alert(key + " = " + obj[key]);
});
于 2012-11-06T06:56:53.563 回答
1

您可以计算属性:

Object.keys(obj).length

请参阅堆栈问题:如何有效地计算 JavaScript 中对象的键/属性的数量?

于 2012-11-06T06:57:14.523 回答