通过动态JSON字符串循环

时间:2011-03-28 13:59:12

标签: jquery json

我有一个POST请求,它接收一个JSON字符串作为结果。字段,值或数组的深度是多少?这些都是未知的。所以,我需要遍历每个json值,它的索引和它的值,并根据它执行操作。

$.post(
    "test.php", 
    { action: 'someaction', param: '2' },
    function(data) {
      //now data is a json string
      $.each(data, function() {
       key = data.key; //i need to retrieve the key
       value = data.value; //i need to retrieve the value also

       //now below here, I want to perform action, based on the values i got as key and values
      }
    },
    "json"
);

如何将JSON的值分隔为keyvalue

3 个答案:

答案 0 :(得分:5)

对不起,伙计们,但我自己解决了。请不要生我的气。 (如果社区需要,我会删除该问题。)

$.post(
    "test.php", 
    { action: 'someaction', param: '2' },
    function(data) {
      //now data is a json string
      $.each(data, function(key,value) {
       alert(key+value);
       //now below here, I want to perform action, based on the values i got as key and values
      }
    },
    "json"
);

答案 1 :(得分:3)

好吧,JSON被解析为JavaScript对象。您可以使用for...in遍历它们:

for(var key in data) {
    if(data.hasOwnProperty(key)) {
        var value = data[key];
    }
}

答案 2 :(得分:0)