Jak iterować strukturę JSON? [duplikat]

to pytanie ma już odpowiedzi tutaj : For-each over an array in JavaScript (40 odpowiedzi) Zamknięty 3 lata temu .

Mam następującą strukturę JSON:

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

Jak to zrobić używając JavaScript?

Author: John, 2009-07-03

13 answers

Pobrane z 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));
});
 444
Author: Marquis Wang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-02 10:13:33

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);
  }
}

Uwaga: metoda for-in jest fajna dla prostych obiektów. Niezbyt Inteligentny w użyciu z obiektem DOM.

 537
Author: Your Friend Ken,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-28 10:22:08

Użyj dla...z :

var mycars = [{name:'Susita'}, {name:'BMW'}];

for (var car of mycars) 
{
  document.write(car.name + "<br />");
}

Wynik:

Susita
BMW
 98
Author: AlikElzin-kilaka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-28 08:35:49

Proszę dać mi znać, jeśli nie jest to łatwe:

var jsonObject = {
  name: 'Amit Kumar',
  Age: '27'
};

for (var prop in jsonObject) {
  alert("Key:" + prop);
  alert("Value:" + jsonObject[prop]);
}
 75
Author: abdulbasit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-29 13:47:08

If this is your dataArray:

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

Wtedy:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
         var ID = this.id;
         var CLASS = this.class;
});
 41
Author: Swapnil Godambe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-22 13:59:47

Skopiowane i wklejone z http://www.w3schools.com , nie ma potrzeby stosowania jQuery.

var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
    text += person[x];
}

Wynik: 25

 19
Author: Gerrit Brink,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-09 13:46:57

Przykład Mootools:

var ret = JSON.decode(jsonstr);

ret.each(function(item){
    alert(item.id+'_'+item.classd);
});
 18
Author: Jason,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-03 07:19:17

Z zagnieżdżonymi obiektami można go odzyskać jako funkcję rekurencyjną:

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

Gdzie as events jest obiektem json.

 12
Author: Fatima Zohra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-22 07:47:37

Możesz użyć mini biblioteki jak objx - http://objx.googlecode.com/

Możesz napisać kod w następujący sposób:

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()

Dostępnych jest więcej "wtyczek", które umożliwiają obsługę takich danych, zobacz http://code.google.com/p/objx-plugins/wiki/PluginLibrary

 11
Author: Mat Ryer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-03 14:51:41

To jest czysty, skomentowany przykład 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 + "<br/>";
                    }
                }
            }

            hr.send(null); 
        }
</script>
<script language="JavaScript" type="text/javascript">iterate_json();</script>// call function here
 10
Author: karto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-11 14:47:07

Markiz Wang może być najlepszą odpowiedzią podczas korzystania z jQuery.

Tutaj jest coś podobnego w czystym JavaScript, przy użyciu metody forEach JavaScript. forEach przyjmuje funkcję jako argument. Funkcja ta zostanie wywołana dla każdego elementu w tablicy, z tym elementem jako argumentem.

Krótkie i łatwe:

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

results.forEach(function(item) {
    console.log(item);
});
 10
Author: Fabien Snauwaert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-27 22:20:16

Innym rozwiązaniem do poruszania się po dokumentach JSON jest JSONiq (zaimplementowany w silniku Zorba), gdzie można napisać coś w stylu:

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" :)

Możesz go uruchomić na http://try.zorba.io/

 5
Author: Ghislain Fourny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-22 07:18:06

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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 5
Author: Vaughn Gavin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-28 06:57:46