使用getjson读取json数据

Read json data using getjson

本文关键字:数据 json 读取 getjson 使用      更新时间:2023-09-26

我有一个json文件:

{
  "bible" : {
    "@attributes" : {
      "translation" : "ASV"
    },
    "testament" : [
      {
        "@attributes" : {
          "name" : "Old"
        },
        "book" : [
          {
            "@attributes" : {
              "name" : "Genesis"
            }
          },
          {
            "@attributes" : {
              "name" : "Exodus"
            }
          },
          {
            "@attributes" : {
              "name" : "Leviticus"
            }
          },
          {
            "@attributes" : {
              "name" : "Numbers"
            }
          },
          {
            "@attributes" : {
              "name" : "Deuteronomy"
            }
          },
          {
            "@attributes" : {
              "name" : "Joshua"
            }
          },
          {
            "@attributes" : {
              "name" : "Judges"
            }
          },
          {
            "@attributes" : {
              "name" : "Ruth"
            }
          }
        ]
      }
    ]
  }
}

我正在使用代码来阅读它:

$(document).ready(function(){
   $.getJSON("asv/index.json", function(json) {
       alert("JSON Data: " + json.bible.testament[1].name);
     });
});

但这让我无法定义。请让我知道如何读书名。@attributes还有什么用?感谢

试试这个:

 $.getJSON('asv/index.json', 
function(json) {
    $.each(json.bible.testament[0].book,  // $.each() looping on each books
    function(i, value) {
        console.log(value['@attributes'].name);  // here you get the name of books
    });

json.bible.testament[1].name未定义。

尝试json.bible.testament[1]['@attributes'].name

数据的对象路径错误。我建议您将json数据粘贴到查看器中,以便更容易地查看需要获得的内容。尝试http://jsonviewer.stack.hu/例如

<script type="text/javascript">
$(document).ready(function(){
    $.getJSON("asv/index.json", function(json) {
        alert(json.bible.testament[0]['@attributes'].name);
        alert(json.bible.testament[0].book[0]['@attributes'].name);
    });
});
</script>

这对我很有用。注意你没有任何testament[1]索引,只有testament[0]

@attributes部分似乎是生成JSON的脚本正在创建的东西,不需要使用JSON。如果我有权访问JSON创建脚本,我会删除它,但也许它在您看不到的某些系统中使用。

如果你有一个支持console.log的浏览器(例如Firefox),你可以做一个"console.log(json)"并查看其结构
你可以访问这样的名称:

json.bible.colent[0].book[0]['@attributes'].name
json.bible.colent[0].book[1]['@attributes'].name