使用js从json文件创建嵌套列表

时间:2017-07-16 12:46:30

标签: javascript json

我有一个示例如下的示例json文件:

{
    "PetOwners": [
        {
        "name":"John",
        "age":31,
        "pets":[
            { "animal":"dog", "name":"Fido" },
            { "animal":"cat", "name":"Felix" },
            { "animal":"hamster", "name":"Lightning" }
        ]
        },
        {
        "name":"Albert",
        "age":29,
        "pets":[
            { "animal":"iquana", "name":"bart" },
            { "animal":"rooster", "name":"Callie" },
            { "animal":"weasel", "name":"Jonathan" }
        ]
        },
        {
        "name":"Sally",
        "age":32,
        "pets":[
            { "animal":"cat", "name":"Abbott" },
            { "animal":"bird", "name":"Buzz" },
            { "animal":"rabbit", "name":"Hoppity" }
            ]
        }
    ]
}

我想从这些项目中创建一个HTML列表,这些项目将显示宠物主人姓名以及他们名字下面的宠物缩进列表。我已经能够为名称创建一个列表,但是如何在每个名称下创建所有者宠物的缩进列表?以下是我到目前为止的情况。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Reading a JSON file</title>
</head>
<body>

<h2>Reading a JSON file.</h2>
<ul id="demo"></ul>
<script>
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            var x = document.getElementById("demo");
            for (i=0; i<myObj.PetOwners.length; i++){
                var opt = myObj.PetOwners[i].name;
                var el = document.createElement("LI");
                el.textContent = opt;
                el.value = opt;
                x.appendChild(el);
            }
        }
    };
    xmlhttp.open("GET", "http://example.com/json/json_demo.json", true);
    xmlhttp.send();
</script>


</body>
</html>

3 个答案:

答案 0 :(得分:0)

var data = {
    "PetOwners": [
        {
        "name":"John",
        "age":31,
        "pets":[
            { "animal":"dog", "name":"Fido" },
            { "animal":"cat", "name":"Felix" },
            { "animal":"hamster", "name":"Lightning" }
        ]
        },
        {
        "name":"Albert",
        "age":29,
        "pets":[
            { "animal":"iquana", "name":"bart" },
            { "animal":"rooster", "name":"Callie" },
            { "animal":"weasel", "name":"Jonathan" }
        ]
        },
        {
        "name":"Sally",
        "age":32,
        "pets":[
            { "animal":"cat", "name":"Abbott" },
            { "animal":"bird", "name":"Buzz" },
            { "animal":"rabbit", "name":"Hoppity" }
            ]
        }
    ]
};

var html = data["PetOwners"].map(function(owner){
  var res = "<li>" + owner["name"];
  res += "<ul>";
  res += owner["pets"].map(function(pet){
    return "<li>" + pet["name"] + " -> (" + pet["animal"] + ")</li>";
  }).join("");
  return res + "</ul></li>";
});

document.body.innerHTML = html;
// console.log(html);

// Or
 var ul_ = childs => {
	var res = document.createElement("ul");
  childs.forEach( c => res.appendChild(c) );
  return res;
}

var li_ = title => {
	var res = document.createElement("li");
  res.textContent = title;
  return res;
}
var list = ul_( data["PetOwners"].map(function(owner){
  var res = li_(owner["name"]);
  res.appendChild( ul_(owner["pets"].map(function(pet){
    return li_( pet["name"] + " -> " + pet["animal"] );
  }) ) );
  return res;
}) );

document.body.appendChild(list);

答案 1 :(得分:0)

代码很简单。只需重复与外循环相同的循环。

以下是相同的样本。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Reading a JSON file</title>
</head>
<body>

<h2>Reading a JSON file.</h2>
<ul id="demo"></ul>
<script>

   var myObj = {
    "PetOwners": [
        {
        "name":"John",
        "age":31,
        "pets":[
            { "animal":"dog", "name":"Fido" },
            { "animal":"cat", "name":"Felix" },
            { "animal":"hamster", "name":"Lightning" }
        ]
        },
        {
        "name":"Albert",
        "age":29,
        "pets":[
            { "animal":"iquana", "name":"bart" },
            { "animal":"rooster", "name":"Callie" },
            { "animal":"weasel", "name":"Jonathan" }
        ]
        },
        {
        "name":"Sally",
        "age":32,
        "pets":[
            { "animal":"cat", "name":"Abbott" },
            { "animal":"bird", "name":"Buzz" },
            { "animal":"rabbit", "name":"Hoppity" }
            ]
        }
    ]
};

var x = document.getElementById("demo");
var outerList = document.createElement('ul');
for (var i=0; i<myObj.PetOwners.length; i++){
    var opt = myObj.PetOwners[i].name;
    var outerListItem = document.createElement("li");
    var innerList = document.createElement('ul');
    for(var j = 0; j < myObj.PetOwners[i].pets.length; j++) {
      var innerListItem = document.createElement('li');
      innerListItem.textContent = myObj.PetOwners[i].pets[j].name;
      innerList.appendChild(innerListItem);
    }
    outerListItem.textContent = opt;
    outerListItem.appendChild(innerList);
    outerList.appendChild(outerListItem);
}

x.appendChild(outerList);

</script>


</body>
</html>

答案 2 :(得分:0)

你可以重复另一个循环

            for(pet = 0; pet < myObj.PetOwners[i].pets.length; pet++) {
                var optIn = myObj.PetOwners[i].pets[pet].animal + ":" + myObj.PetOwners[i].pets[pet].name;
                var elIn = document.createElement("LI");
                elIn.className = "tab"
                elIn.textContent = optIn;
                elIn.value = optIn;
                x.appendChild(elIn);
            }

添加以下css

            <style type="text/css">
                <!--
                .tab { margin-left: 40px; }
                -->
            </style>