简体   繁体   English

解析嵌套json的语法

[英]syntax for parsing a nested json

I am trying to pull data from a json file, with many layers. 我正在尝试从json文件中提取数据,其中包含许多层。 An example is below. 下面是一个示例。

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

I am using the script below to parse the data and search for any pets with the animal type of dog. 我正在使用下面的脚本来解析数据并搜索具有动物类狗的任何宠物。 But it seems like my syntax for the objects is off. 但似乎我的对象语法已关闭。

<!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>

Am I using the operators incorrectly? 我是否使用了错误的运算符?

I think your syntax is wrong 我认为您的语法有误

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

after this 在这之后

myobj.petOwner.pets[0].animal

this gives you the animal key 这给你动物的钥匙

<!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>

the issue is in your if condition 问题出在您的if条件中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM