javascript - 我如何迭代JSON结构?



6 Answers

var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}];

for (var i = 0; i < arr.length; i++){
    var obj = arr[i];
    for (var key in obj){
        var attrName = key;
        var attrValue = obj[key];
    }
}

var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}];
    
for (var i = 0; i < arr.length; i++){
  document.write("<br><br>array index: " + i);
  var obj = arr[i];
  for (var key in obj){
    var value = obj[key];
    document.write("<br> - " + key + ": " + value);
  }
}

注意:for-in方法对于简单对象很酷。 与DOM对象一起使用不太聪明。

javascript jquery json loops

这个问题在这里已经有了答案:

我有以下JSON结构:

[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]

如何使用jQuery或JavaScript来迭代它?




请让我知道,如果这不容易:

    var jsonObject = {
        name: 'Amit Kumar',
        Age: '27'
    };
    for (var prop in jsonObject) {
        alert("Key:" + prop);
        alert("Value:" + jsonObject[prop]);
    }



mootools示例:

var ret = JSON.decode(jsonstr);

ret.each(function(item){
    alert(item.id+'_'+item.classd);
});



您可以使用像objx这样的小型图书馆 - http://objx.googlecode.com/

你可以编写这样的代码:

var data =  [ {"id":"10", "class": "child-of-9"},
              {"id":"11", "class": "child-of-10"}];

// alert all IDs
objx(data).each(function(item) { alert(item.id) });

// get all IDs into a new array
var ids = objx(data).collect("id").obj();

// group by class
var grouped = objx(data).group(function(item){ return item.class; }).obj()

有更多'插件'可供您处理这类数据,请参阅http://code.google.com/p/objx-plugins/wiki/PluginLibrary




使用嵌套对象,可以通过递归函数检索:

function inside(events)
  {
    for (i in events) {
      if (typeof events[i] === 'object')
        inside(events[i]);
      else
      alert(events[i]);
    }
  }
  inside(events);

作为事件是json对象。




浏览JSON文档的另一个解决方案是JSONiq (在Zorba引擎中实现),您可以在其中编写如下内容:

let $json := [ {"id":"10", "class": "child-of-9"},
               {"id":"11", "class": "child-of-10"} ]
for $entry in jn:members($json)     (: binds $entry to each object in turn :)
return $entry("class")              (: gets the value associated with "class" :)

您可以在http://www.zorba-xquery.com/html/demo#AwsGMHmzDgRpkFpv8qdvMjWLvvE=上运行它




Related