[英]syntax for parsing a nested json
我正在嘗試從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>
我是否使用了錯誤的運算符?
我認為您的語法有誤
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>
問題出在您的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.