javascript - 解析嵌套 json 的语法

标签 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>

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

最佳答案

我认为你的语法错误

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/

相关文章:

javascript - Node - 在 For 周期内等待请求响应

javascript - 检查 System.Gadget.Flyout.file 的值

php - 如何在 javascript 中对动态添加的行应用计数器

javascript - 如何将循环中的多个变量传递到 ajax json 数据中。

html - ltr 后的 css rtl 不适用于 chrome

python - 从 json 中删除\r

javascript - 使用下划线js的两个对象数组coffeescript之间的区别

javascript - 防止浏览器弹出窗口警告

html - 加载页面时更改背景颜色

javascript - 如果填充了任何相关对象字段,如何使 ng-required 为真?