Is it possible to validate a JSONPath expression?

2019-09-01 18:41发布

问题:

I want to know if it's possible to validate a JSONPath expression.

My JSONPath is $.phoneNumbers[:1].type

And my json is as follows:

{      
  "phoneNumbers": [
     {
       "type"  : "iPhone",
       "number": "0123-4567-8888"
     },
     {
       "type"  : "home",
       "number": "0123-4567-8910"
     }
  ]
}

I want to know if I am using the right/valid JSONPath expression.

回答1:

You can got to http://jsonpath.curiousconcept.com/ and try it there.

Or you can do it in a programming language.

Here's how you could do it in Ruby, using the jsonpath gem:

require 'jsonpath'

data=<<-EOS
{      "phoneNumbers":
 [
     {
       "type"  : "iPhone",
       "number": "0123-4567-8888"
     },
     {
       "type"  : "home",
       "number": "0123-4567-8910"
     }
 ]
}
EOS

JsonPath.new("$.phoneNumbers[:1].type").on(data)


回答2:

@Parag A - I just wrote a javascript library with which you can query JSON structure with XPath (which is standardised as opposed to JSONPath). Using this XPath evaluator, you can paste in your JSON structure and validate your XPath queries, in-place:

http://www.defiantjs.com/#xpath_evaluator

Putting your question and the answer in javascript code, it'll look something like this:

var obj = {      
  "phoneNumbers": [
     {
       "type"  : "iPhone",
       "number": "0123-4567-8888"
     },
     {
       "type"  : "home",
       "number": "0123-4567-8910"
     }
  ]
};

var qry = JSON.search(obj, '//phoneNumbers[1]/type');
// qry[0] = 'iPhone'

Defiant extends the global object JSON and the search method always returns an array with matching selections (empty array if no matches were found).



标签: jsonpath