如何在js中解析json?

时间:2012-11-06 06:55:09

标签: javascript json

我需要在循环中解析像{"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

2 个答案:

答案 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?