首页 文章

如何迭代JSON结构? [重复]

提问于
浏览
439

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

我有以下JSON结构:

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

如何使用jQuery或JavaScript迭代它?

13 回答

  • 10

    取自jQuery docs

    var arr = [ "one", "two", "three", "four", "five" ];
    var obj = { one:1, two:2, three:3, four:4, five:5 };
    
    jQuery.each(arr, function() {
      $("#" + this).text("My id is " + this + ".");
      return (this != "four"); // will stop running to skip "five"
    });
    
    jQuery.each(obj, function(i, val) {
      $("#" + i).append(document.createTextNode(" - " + val));
    });
    
  • 39
    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对象不是很聪明 .

  • 9

    使用 foreach

    <html>
    <body>
    <script type="text/javascript">
    var mycars = [{name:'Susita'}, {name:'BMW'}];
    for (i in mycars)
    {
      document.write(mycars[i].name + "
    "); } </script> </body> </html>

    将导致:

    Susita
    BMW
    
  • 8

    如果不容易,请告诉我:

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

    如果这是你的 dataArray

    var dataArray = [{"id":28,"class":"Sweden"}, {"id":56,"class":"USA"}, {"id":89,"class":"England"}];
    

    然后:

    $(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
             var ID = this.id;
             var CLASS = this.class;
    });
    
  • 12

    mootools例子:

    var ret = JSON.decode(jsonstr);
    
    ret.each(function(item){
        alert(item.id+'_'+item.classd);
    });
    
  • 4

    http://www.w3schools.com复制并粘贴,不需要JQuery开销 .

    var person = {fname:"John", lname:"Doe", age:25};
    
    var text = "";
    var x;
    for (x in person) {
        text += person[x];
    }
    

    结果:John Doe 25

  • 14

    你可以使用像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()
    

    还有更多'plugins'可用于处理这样的数据,请参阅http://code.google.com/p/objx-plugins/wiki/PluginLibrary

  • 76

    对于嵌套对象,可以通过递归函数进行检索:

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

    事件是json对象的地方 .

  • 2

    这是一个纯注释的JavaScript示例 .

    <script language="JavaScript" type="text/javascript">
      function iterate_json(){
                // Create our XMLHttpRequest object
                var hr = new XMLHttpRequest();
                // Create some variables we need to send to our PHP file
                hr.open("GET", "json-note.php", true);//this is your php file containing json
    
                hr.setRequestHeader("Content-type", "application/json", true);
                // Access the onreadystatechange event for the XMLHttpRequest object
                hr.onreadystatechange = function() {
                    if(hr.readyState == 4 && hr.status == 200) {
                        var data = JSON.parse(hr.responseText);
                        var results = document.getElementById("myDiv");//myDiv is the div id
                        for (var obj in data){
                        results.innerHTML += data[obj].id+ "is"+data[obj].class + "
    "; } } } hr.send(null); } </script> <script language="JavaScript" type="text/javascript">iterate_json();</script>// call function here
  • 404

    使用jQuery时,Marquis Wang可能是最好的答案 .

    这是纯JavaScript中非常相似的东西,使用JavaScript的 forEach 方法 . forEach将函数作为参数 . 然后将为数组中的每个项调用该函数,并将所述项作为参数 .

    简单易行:

    <script>
    var results = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}];
    
    results.forEach( function( item ) {
        console.log( item );
        });
    </script>
    
  • 9

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

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

    你可以在http://try.zorba.io/上运行它

  • 469
    var jsonString = "{\"schema\": {\"title\": \"User Feedback\", \"description\":\"so\", \"type\":\"object\", \"properties\":{\"name\":{\"type\":\"string\"}}}," +
                            "\"options\":{ \"form\":{\"attributes\":{}, \"buttons\":{ \"submit\":{ \"title\":\"It\", \"click\":\"function(){alert('hello');}\" }}} }}";
    var jsonData = JSON.parse(jsonString);
    
    function Iterate(data)
    {
        jQuery.each(data, function (index, value) {
            if (typeof value == 'object') {
                alert("Object " + index);
                Iterate(value);
            }
            else {
                 alert(index + "   :   " + value);
            }
        });
    
    };
    
    Iterate(jsonData);
    

相关问题