jquery - 将HTTP地址放入javascript变量中以进行json解析

标签 jquery json parsing variables

如果我想要这个外部 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 结构变化如下:

  1. 版本一:

    {
        "http://example.org/about" :
        {
            "http://purl.org/dc/elements/1.1/title" : [{"value" : "annas homepage" , "type" : "literal"}]
        }
    }
    
  2. 版本二:

    {
        "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/

相关文章:

javascript - AngularJS ng-show 与 map 一起使用时不会触发

java - 如何使用java跳过带有多个注释结束标记的多行注释

javascript - 从 Destiny Api 解析 JQuery 中的 JSON 对象

c# - 1.2.3是double数据类型

jquery - 如何在 Meteor.js 上应用 jQuery

Jquery 检测 iframe 内 body 标记的更改或 keyup

javascript - Canvas.toDataURL() 受污染的 Canvas 可能无法导出

c# - 将 JSON 反序列化为 C# - 尝试将 JSON 关联数组转换为 Dictionary<string, string>

java - Spring Boot JSON 后 400 错误

json - 如何用自己的JSON转换器替换