[英]Read json data using getjson
I have a json file: 我有一个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"
}
}
]
}
]
}
}
I am using code to read it: 我正在使用代码来阅读它:
$(document).ready(function(){
$.getJSON("asv/index.json", function(json) {
alert("JSON Data: " + json.bible.testament[1].name);
});
});
But this gives me undefined. 但这给了我不确定的。 Please let me know how to read book names.
请让我知道如何阅读书名。 Also @attributes are what for?
@attributes也适用于什么? Thanks
谢谢
try this: 尝试这个:
$.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
});
You have the wrong object path to your data. 您的数据的对象路径错误。 I recommend that you paste your json data into a viewer to make it easier to see what you need to get.
我建议您将json数据粘贴到查看器中,以便更容易看到您需要获取的内容。 Try http://jsonviewer.stack.hu/ for example.
以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>
That works for me. 这对我行得通。 Notice how you don't have any
testament[1]
index, only testament[0]
. 注意你没有任何
testament[1]
索引,只有testament[0]
。
The @attributes part seems to be something the script that generates the JSON is creating, nothing you need to use JSON per say. @attributes部分似乎是生成JSON的脚本正在创建的,你不需要使用JSON。 I would remove it if I had access to the JSON-creating script, but perhaps it is used in some system that you do not see.
如果我有权访问JSON创建脚本,我会删除它,但也许它会在你看不到的某个系统中使用。
json.bible.testament[1].name
is undefined. json.bible.testament[1].name
未定义。
try json.bible.testament[1]['@attributes'].name
试试
json.bible.testament[1]['@attributes'].name
If you have a browser that supports console.log (Firefox for example) you can do a 'console.log(json)' and look at the structure. 如果您的浏览器支持console.log(例如Firefox),您可以执行'console.log(json)'并查看结构。
You can access names like that: 你可以访问这样的名字:
json.bible.testament[0].book[0]['@attributes'].name json.bible.testament [0] .book [0] [ '@属性']。名
json.bible.testament[0].book[1]['@attributes'].name json.bible.testament [0] .book [1] [ '@属性']。名
... ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.