2

I know how to use JSONPath in JavaScript 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"]

But how to filter on the keys? I want to have all values returned where the key ends in *_url. The following doesn't work since @ apparently only contains the value of the JSON objects.

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

If it's not possible with JSONPath or JSONQuery, is there another library that's easy to use and setup? I want the user to enter the query-expression, that's why I'd prefer to use a query language instead of just evaling plain JavaScript (like these guys).

Community
  • 1
  • 1
mb21
  • 34,845
  • 8
  • 116
  • 142

1 Answers1

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/

Hakan Bilgin
  • 1,113
  • 12
  • 11