2

我知道如何在 JavaScript 中使用 JSONPath来过滤值

var o = {
  current_user_url: "https://api.github.com/user",
  other_user_url: "https://api.github.com/user",
  otherstuff: "stuff"
};
jsonPath(o, "$.[?(/https.*/.test(@))]") //returns ["https://api.github.com/user"]

但是如何过滤键?我希望返回键以 . 结尾的所有值*_url。以下内容不起作用,因为@显然只包含 JSON 对象的值。

jsonPath(o, "$.[?(/.*_url/.test(@))]")

如果 JSONPath 或 JSONQuery 无法实现,是否还有其他易于使用和设置的库?我希望用户输入查询表达式,这就是为什么我更喜欢使用查询语言而不是仅仅评估纯 JavaScript(比如这些家伙)。

4

1 回答 1

1

You can use DefiantJS (http://defiantjs.com) which extends the global object JSON with the method "search". With this method, you can search a JSON structure with XPath syntax and it returns the matches as an array-like object.

var data = {
  current_user_url: "https://api.github.com/user",
  other_user_url: "https://api.github.com/user",
  otherstuff: "stuff"
},
found = JSON.search(data, "//*[substring(name(), string-length(name())-3) = '_url']"),
str = '';

for (var i=0; i<found.length; i++) {
    str += found[i] +'<br/>';
}

document.getElementById('output').innerHTML = str;

To see this in action, check out this fiddle; http://jsfiddle.net/hbi99/92vCL/

于 2014-05-18T12:01:07.137 回答