javascript - 迭代嵌套的 JSON 对象

标签 javascript jquery json django-rest-framework

使用 Edmunds API (edmunds.mashery.io),我正在尝试解析汽车对象。
正如您所看到的,JSON 响应被很好地格式化为以下嵌套树: 制作(id,名称,型号)-->模型(id,名称,nicename,样式)-->样式

考虑到这一点,请考虑以下 API 响应:

{
"name": "BMW",
"model": [
    {
        "id": "BMW_2_Series",
        "name": "2 Series",
        "nicename": "2-series",
        "styles": [
            {
                "id": 200744428,
                "name": "228i 2dr Coupe (2.0L 4cyl Turbo 6M)",
                "drivenwheels": "rear wheel drive",
                "numofdoors": 2,
                "manufacturercode": "162A",
                "engine": 200744477,
                "transmission": 200744479,
                "trim": "228i",
                "pricebasemsrp": "32850.0",
                "pricebaseinvoice": "30720.0",
                "pricedeliverycharges": "995.0",
                "submodelbody": "Coupe",
                "submodelname": "2 Series Coupe",
                "submodelnicename": "coupe",
                "mpghighway": "34",
                "mpgcity": "22",
                "categoriesmarket": "Luxury,Performance",
                "epaclass": "Subcompact Cars",
                "vehiclesize": "Compact",
                "crossover": "NA",
                "primarybodytype": "Car"
            },
            {
                "id": 200744429,
                "name": "228i SULEV 2dr Coupe (2.0L 4cyl Turbo 8A)",
                "drivenwheels": "rear wheel drive",
                "numofdoors": 2,
                "manufacturercode": "162B",
                "engine": 200744475,
                "transmission": 200744478,
                "trim": "228i SULEV",
                "pricebasemsrp": "32850.0",
                "pricebaseinvoice": "30720.0",
                "pricedeliverycharges": "995.0",
                "submodelbody": "Coupe",
                "submodelname": "2 Series Coupe",
                "submodelnicename": "coupe",
                "mpghighway": "35",
                "mpgcity": "23",
                "categoriesmarket": "Luxury,Performance",
                "epaclass": "Subcompact Cars",
                "vehiclesize": "Compact",
                "crossover": "NA",
                "primarybodytype": "Car"
            }]},
    {
        "id": "BMW_3_Series",
        "name": "3 Series",
        "nicename": "3-series",
        "styles": [
            {
                "id": 200729833,
                "name": "320i 4dr Sedan (2.0L 4cyl Turbo 8A)",
                "drivenwheels": "rear wheel drive",
                "numofdoors": 4,
                "manufacturercode": "16TI",
                "engine": 200741606,
                "transmission": 200741614,
                "trim": "320i",
                "pricebasemsrp": "33150.0",
                "pricebaseinvoice": "31000.0",
                "pricedeliverycharges": "995.0",
                "submodelbody": "Sedan",
                "submodelname": "3 Series Sedan",
                "submodelnicename": "sedan",
                "mpghighway": "36",
                "mpgcity": "24",
                "categoriesmarket": "Luxury",
                "epaclass": "Compact Cars",
                "vehiclesize": "Midsize",
                "crossover": "NA",
                "primarybodytype": "Car"
            }
       }
}  

使用 JQuery 的 ajax,我能够加载 JSON 响应。我正在尝试根据模型的 id 创建动态按钮(每个模型都是一个盒装容器,其中包含有关从此响应填充的模型的信息。

我当前的问题是,当我尝试迭代 JQuery 的 .each 时,我得到:
关键:型号
值:[对象] [对象] ... [对象]

我想要完成的是以动态方式访问对象的内容并填充它。

除了这个问题的范围之外,我还有一个基于大局的更普遍的问题:

使用 Edmund 的 API 我计划使用以下按钮制作一个汽车选择网站:
状态1:Make已填充,当选择make时,转到状态2。
状态 2:模型按钮从 JSON API 填充,移至状态 3。

这是我当前的 jQuery 函数:

$.getJSON('http://127.0.0.1:8000/makes/200000081.json', function( models ) {
      console.log(models.model[0].name)

  });

这是我的输出:

2 Series

如果我将 model[0] 更改为 model[3],结果会发生变化(这是应该的。) 如何在可以使用 HTML 操作的数组中获取 model[x].name?

最佳答案

也许这样的事情会有所帮助。

var response = {
"name": "BMW",
"model": [
    {
        "id": "BMW_2_Series",
        "name": "2 Series",
        "nicename": "2-series",
        "styles": [
            {
                "id": 200744428,
                "name": "228i 2dr Coupe (2.0L 4cyl Turbo 6M)",
                "drivenwheels": "rear wheel drive",
                "numofdoors": 2,
                "manufacturercode": "162A",
                "engine": 200744477,
                "transmission": 200744479,
                "trim": "228i",
                "pricebasemsrp": "32850.0",
                "pricebaseinvoice": "30720.0",
                "pricedeliverycharges": "995.0",
                "submodelbody": "Coupe",
                "submodelname": "2 Series Coupe",
                "submodelnicename": "coupe",
                "mpghighway": "34",
                "mpgcity": "22",
                "categoriesmarket": "Luxury,Performance",
                "epaclass": "Subcompact Cars",
                "vehiclesize": "Compact",
                "crossover": "NA",
                "primarybodytype": "Car"
            },
            {
                "id": 200744429,
                "name": "228i SULEV 2dr Coupe (2.0L 4cyl Turbo 8A)",
                "drivenwheels": "rear wheel drive",
                "numofdoors": 2,
                "manufacturercode": "162B",
                "engine": 200744475,
                "transmission": 200744478,
                "trim": "228i SULEV",
                "pricebasemsrp": "32850.0",
                "pricebaseinvoice": "30720.0",
                "pricedeliverycharges": "995.0",
                "submodelbody": "Coupe",
                "submodelname": "2 Series Coupe",
                "submodelnicename": "coupe",
                "mpghighway": "35",
                "mpgcity": "23",
                "categoriesmarket": "Luxury,Performance",
                "epaclass": "Subcompact Cars",
                "vehiclesize": "Compact",
                "crossover": "NA",
                "primarybodytype": "Car"
            }]},
    {
        "id": "BMW_3_Series",
        "name": "3 Series",
        "nicename": "3-series",
        "styles": [
            {
                "id": 200729833,
                "name": "320i 4dr Sedan (2.0L 4cyl Turbo 8A)",
                "drivenwheels": "rear wheel drive",
                "numofdoors": 4,
                "manufacturercode": "16TI",
                "engine": 200741606,
                "transmission": 200741614,
                "trim": "320i",
                "pricebasemsrp": "33150.0",
                "pricebaseinvoice": "31000.0",
                "pricedeliverycharges": "995.0",
                "submodelbody": "Sedan",
                "submodelname": "3 Series Sedan",
                "submodelnicename": "sedan",
                "mpghighway": "36",
                "mpgcity": "24",
                "categoriesmarket": "Luxury",
                "epaclass": "Compact Cars",
                "vehiclesize": "Midsize",
                "crossover": "NA",
                "primarybodytype": "Car"
            }
          ]
       }
  ]
}
 var model = response.model;
 var brandname = response.name;
 $(model).each(function(){
   var series = $(this).get(0);
   $("#view").append("<button id=\""+series.id+"\" name=\""+series.id+"\">"+brandname+" "+series.name+"</button>");
   $(document).on("click","#"+series.id,function() { 
	   $(series.styles).each(function(){
	   var make = $(this).get(0);
	   if($("#"+make.id).length<=0) {
	      $("#subview").append("<button id=\""+make.id+"\" name=\""+make.id+"\">"+make.name+"</button>");
		  } else {
		  $("#"+make.id).remove();
		  }
		$(document).on("click","#"+make.id,function() { 
		var carinfo = "";
		for (var prop in make) {
		  carinfo += prop+' = '+make[prop]+"\n";
		}
		alert(carinfo);
		});
       });
   });   
   });
#view button,#subview button{
  width:100%;
  display:block;
  padding:2rem;
}
#view button {
  color:#fff;
  background-color:#326d1a;
}
#subview button{
  color:#fff;
  background-color:#a22fa1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="view"></div>
<div id="subview"></div>

关于javascript - 迭代嵌套的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41942133/

相关文章:

javascript - HTML 和 CSS 和 Javascript : How to make a onclick even remove text in input text fields

javascript - Edge 浏览器中的 focus()

javascript - 如何按值将数据传递到延迟 then 处理程序?

javascript - 如何避免使用 java 脚本重置页面刷新/页面加载时的计时器值?

javascript - Grails从 View 访问 Controller 值

android - 从 Kotlin android 中的 json 字符串中删除换行符\n

javascript - 我如何使用angularJS从JSON结果中提取对象

php - JSON 编码将数组乘以单个数组

javascript - 获取 requireJS 模块 URL

javascript - 我如何检查使用 jQuery 滚动了多少元素?