简体   繁体   中英

syntax for parsing a nested json

I am trying to pull data from a json file, with many layers. 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(myObj.petOwner[i].pets.animal == 'dog'){
//this should be like this
if(myObj.petOwner.pets[i].animal == 'dog'){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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