我正在尝试从具有多层的 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
这会给你动物 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>
关于javascript - 解析嵌套 json 的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46908630/