Is it possible to validate a JSONPath expression?

倾然丶 夕夏残阳落幕 提交于 2019-12-11 19:38:44

问题


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



来源:https://stackoverflow.com/questions/18922494/is-it-possible-to-validate-a-jsonpath-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!