【问题标题】:syntax for parsing a nested json解析嵌套 json 的语法
【发布时间】:2017-10-24 19:00:39
【问题描述】:

我正在尝试从包含多个层的 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>

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

【问题讨论】:

  • json文件是否有开括号{和}
  • 我想你的意思是写myObj.petOwner.pets[i].animal而不是myObj.petOwner[i].pets.animal
  • 那不是有效的 JSON

标签: javascript html json xmlhttprequest


【解决方案1】:

我认为你的语法是错误的

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>

【讨论】:

  • 那不是 JSON
  • 我实现了对 if 语句的更改,但是当我检查控制台日志时。我得到一个未定义的值。我想知道在引用深度嵌套项时是否需要更改语法?
【解决方案2】:

问题在于你的 if 条件

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多