我有以下JSON结构:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
我如何使用JavaScript迭代它?
我有以下JSON结构:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
我如何使用JavaScript迭代它?
当前回答
这是一个纯注释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
其他回答
如果不容易,请告诉我:
var jsonObject = {
name: 'Amit Kumar',
Age: '27'
};
for (var prop in jsonObject) {
alert("Key:" + prop);
alert("Value:" + jsonObject[prop]);
}
另一个在JSON文档中导航的解决方案是JSONiq(在Zorba引擎中实现),在那里你可以写这样的东西:
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://public.rumbledb.org:9090/public.html上运行它
对于嵌套对象,可以通过递归函数检索:
function inside(events)
{
for (i in events) {
if (typeof events[i] === 'object')
inside(events[i]);
else
alert(events[i]);
}
}
inside(events);
其中as events是json object。
mootools的例子:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});
王侯的问题可能是使用jQuery时的最佳答案。
下面是纯JavaScript中非常类似的东西,使用JavaScript的forEach方法。forEach以函数作为参数。然后,将为数组中的每个项调用该函数,并将该项作为参数。
简短而简单:
var结果= [{" id ":“10”,“类”:“child-of-9”},{" id ":“十一”,“classd”:“child-of-10”}); results.forEach(函数(项){ console.log(项); });