用于解析嵌套json的语法

时间:2017-10-24 10:52:48

标签: javascript html json xmlhttprequest

我正在尝试从包含多个图层的json文件中提取数据。下面是一个例子。

- "petOwner": {
           "name":"John",
           "age":31,
           "pets":[
                   { "animal":"dog", "name":"Fido" },
                   { "animal":"cat", "name":"Felix" },
                   { "animal":"hamster", "name":"Lightning" }
                  ]
              }

我使用下面的脚本来解析数据并搜索任何带有动物类型狗的宠物。但似乎我的对象语法已关闭。

<!DOCTYPE html>
<html>
<body>

<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>

<p id="demo"></p>

<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var i;
var myObj = JSON.parse(this.responseText);
for(i = 0; i < myObj.petOwner.pets.length; i++) {
if(myObj.petOwner[i].pets.animal == 'dog'){

document.getElementById("demo").innerHTML = myObj.petOwner[i].pets.name;
    }
    }
 }
};
xmlhttp.open("GET", "jsonExample.txt", true);
xmlhttp.send();


</script>

<p>Take a look at <a href="jsonExample.txt" target="_blank">json_demo</a></p>

</body>
</html>

我是否错误地使用了运算符?

2 个答案:

答案 0 :(得分:1)

我认为你的语法错了

var myobj={"petOwner": {
           "name":"John",
           "age":31,
           "pets":[
                   { "animal":"dog", "name":"Fido" },
                   { "animal":"cat", "name":"Felix" },
                   { "animal":"hamster", "name":"Lightning" }
                  ]
              }}

之后

myobj.petOwner.pets[0].animal

这会给你动物钥匙

<!DOCTYPE html>
<html>
<body>

<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>

<p id="demo"></p>

<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var i;
var myObj = JSON.parse(this.responseText);
for(i = 0; i < myObj.petOwner.pets.length; i++) {
if(myObj.petOwner.pets[i].animal == 'dog'){

document.getElementById("demo").innerHTML = myObj.petOwner.pets[i].name;
    }
    }
 }
};
xmlhttp.open("GET", "jsonExample.txt", true);
xmlhttp.send();


</script>

<p>Take a look at <a href="jsonExample.txt" target="_blank">json_demo</a></p>

</body>
</html>

答案 1 :(得分:0)

问题出在你的if条件

if(myObj.petOwner[i].pets.animal == 'dog'){
//this should be like this
if(myObj.petOwner.pets[i].animal == 'dog'){