如果我想要这个外部 json 文件:
{
"http://example.org/about" :
{
"http://purl.org/dc/elements/1.1/title" : [{"value" : "annas homepage" , "type" : "literal"}]
}
}
这个外部 jquery 脚本在 json 文件中获取书名:
var a = 'http://example.org/about'
var b = 'http://purl.org/dc/elements/1.1/title'
$(document).ready(function() {
$("#trigger").click(function(event) {
$.getJSON('rdfjson.json', function(json) {
$('#meta').html('Title: ' + json.a.b[0].value);
});
});
});
这个 HTML 代码:
<p>Click on the button to fetch data from json structure:</p>
<div id="meta">
This text will be overwritten.
</div>
<input type="button" id="trigger" value="Load Data" />
为什么不起作用?当我在 json 文档和脚本中使用普通字符串时,它工作正常。
此外,我不明白如何迭代整个 json 文件,例如,如果它更复杂或元素具有包含数据等的长向量等。
非常感谢!
最佳答案
因为您正在寻找名为a
的对象成员,而不是名称为存储在变量“a”中的值的对象成员.
不要使用“点表示法”,而是使用“方括号表示法”
$('#meta').html('Title: ' + json[a][b][0].value);
有关更多信息,请参见此处:http://www.dev-archive.net/articles/js-dot-notation/
编辑:
如果 JSON 结构变化如下:
版本一:
{ "http://example.org/about" : { "http://purl.org/dc/elements/1.1/title" : [{"value" : "annas homepage" , "type" : "literal"}] } }
版本二:
{ "http://somewhereelse.com/something" : { "http://anotherplace.org/dc/blah-blah-blah/title" : [{"value" : "annas homepage" , "type" : "literal"}] } }
例如总是有一个对象,该对象具有一个成员,而该对象又具有一个成员
...并且您需要定位它:
$.getJSON('rdfjson.json', function(obj) {
for (var x in obj) {
if (obj.hasOwnProperty(x)) {
var obj2 = obj[x];
for (var x in obj2) {
if (obj2.hasOwnProperty(x)) {
$('#meta').html('Title: ' + obj2[x][0].value);
}
}
}
}
});
如果您了解有关需要遍历的路径的更多信息,您当然可以在 for
循环中添加条件:
$.getJSON('rdfjson.json', function(obj) {
for (var x in obj) {
// if you know you're looking for a key that begins with "http://"
if (obj.hasOwnProperty(x) && x.indexOf("http://") === 0) {
var obj2 = obj[x];
for (var x in obj2) {
// Check that the value is an array of at least length 1, and whose 1st value has the property "value".
if (obj2.hasOwnProperty(x) && obj2[x] instanceof Array && obj2[x].length > 0 && obj2[x][0].value) {
$('#meta').html('Title: ' + obj2[x][0].value);
}
}
}
}
});
关于jquery - 将HTTP地址放入javascript变量中以进行json解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6912810/