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).

2
  • your intention is to verify attribute name for a specific pattern? or get list of attribute names? Commented May 14, 2014 at 12:59
  • I want to have all values returned where the key ends in *_url. Commented May 14, 2014 at 13:22

1 Answer 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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.