我知道如何在 JavaScript 中使用 JSONPath to filter on the values :
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(如 these guys )。
最佳答案
您可以使用 DefiantJS ( http://defiantjs.com ),它使用“search”方法扩展全局对象 JSON。使用此方法,您可以使用 XPath 语法搜索 JSON 结构,并将匹配结果作为类似数组的对象返回。
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;
要查看实际效果,请查看此 fiddle ; http://jsfiddle.net/hbi99/92vCL/
关于javascript - 键上的 JSONPath/JSONQuery 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23631754/