我试图在 AJAX 调用中使用 jQuery 遍历 JSON 对象,然后在 html 页面中打印这些对象。我遇到了this stackoverflow post that shows you how to loop through json objects .这在一定程度上起作用了。
我能够显示 id": 1 对象的所有值,但之后我无法尝试显示更多值。例如,我想显示存储在"id"中的值: 2 等等。
JSON数据由https://openhardwaremonitor.org生成软件。
这是 JSON 数据在短版本中的样子,这里是 full version
{
"id": 0,
"Text": "Sensor",
"Min": "Min",
"Value": "Value",
"Max": "Max",
"ImageURL": "",
"Children": [
{
"id": 1,
"Text": "LAPTOP-4CG0QVS4",
"Min": "",
"Value": "",
"Max": "",
"ImageURL": "images_icon/computer.png",
"Children": [
{
"id": 2,
"Text": "ASUS FX504GM",
"Min": "",
"Value": "",
"Max": "",
"ImageURL": "images_icon/mainboard.png",
"Children": []
},
{
"id": 3,
"Text": "Intel Core i7-8750H",
"Min": "",
"Value": "",
"Max": "",
"ImageURL": "images_icon/cpu.png",
"Children": [
{
"id": 4,
"Text": "Clocks",
"Min": "",
"Value": "",
"Max": "",
"ImageURL": "images_icon/clock.png",
"Children": [
{
这是我目前拥有的代码
<script>
var url = 'https://api.myjson.com/bins/sa41o';
$.ajax({
url: url,
method: 'GET',
}).done(function (result) {
var data = result.Children;
//console.log(result.Children.length);
var i = 0;
var hosData = "<table border='1'>";
hosData += "<tr>";
hosData += "<th>";
hosData += 'id';
hosData += "</th>";
hosData += "<th>";
hosData += 'Text';
hosData += "</th>";
hosData += "<th>";
hosData += 'Min';
hosData += "</th>";
hosData += "<th>";
hosData += 'Value';
hosData += "</th>";
hosData += "<th>";
hosData += 'Max';
hosData += "</th>";
hosData += "<th>";
hosData += 'ImageURL';
hosData += "</th>";
hosData += "</tr>";
for (i = 0; i < data.length; i++) {
hosData += "<tr>";
hosData += "<td>";
hosData += data[i].id;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].Text;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].Min;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].Value;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].Max;
hosData += "</td>";
hosData += "<td>";
hosData += data[i].ImageURL;
hosData += "</td>";
hosData += "</tr>";
}
hosData += "</table>";
$("#data").html(hosData);
}).fail(function (err) {
throw err;
});
<script
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data">
</div>
我似乎无法解决这个问题。
var data = result.Children
返回长度为 1,这是这里的问题,因为我期望长度大于 1。
最佳答案
您可以使用下面的代码,具体取决于您想要的子项目
假设您已将 json 对象保存在名为“json_data”的 js var 中
for (item in json_data) {
for (subItem in Children[item]) {
alert(json_data[item][subItem].id);
}
}
关于javascript - 如何循环遍历具有许多 JSON 数组节点的 JSON 对象 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53726634/