8

Hi I am trying to find a way to validate jsonpath entered by user before evaluating it. I was hoping use something like a regex to do that but so far I could not find any doc/resource on how to validate jsonpath syntax.

All searched return resources that talk about evaluating the expression. Even the jayway.JsonPath library does not seem to do any syntax check.

Is it not possible to do a syntax check for jsonpath syntax ? If it is possible can you please point me in the right direction.

Rajind Ruparathna
  • 2,215
  • 24
  • 55
  • 2
    Jsonpath has its own syntax, so there's probably no way around an actual jsonpath parser. Regex is not a good fit for this kind of task, because it's a *pattern matcher*, not a parser. – Bohemian Oct 14 '16 at 01:11
  • @Bohemian I'm not experienced in this at all. I would like to know whether it is possible to implement a syntax parser for jsonpath ? – Rajind Ruparathna Dec 04 '16 at 18:07
  • 2
    Try importing [Jayway JsonPath](https://github.com/jayway/JsonPath) then `JsonPath.read("{}", yourJsonPath);` and if it doesn't explode the path is valid. – Bohemian Dec 04 '16 at 18:36

3 Answers3

1

try JsonPath.compile("$.path")

VG P
  • 337
  • 3
  • 9
0

Depending on the language you are using, you could use try-catch, but since you have said you are looking for a specific error message, you should check if the function returns an error message to check. You can also try taking a look at this GitHub project by ashphy. It is JSONPath validator that may work for you.

Beckett O'Brien
  • 176
  • 2
  • 16
0

I tried to create a JSON path expression validator based off of Stefan Goessner's article and JS implementation.

The code is hosted on the Github repository at jsonpath-syntax-validator

Following is a sample usage of the library. It doesn't evaluate against a JSON object –– it's a strictly superficial check. However, in my opinion Jayway's JsonPath would be a better choice in case evaluation of the path expression is needed.

JsonPathValidator validator = new BasicJsonPathValidator();
Assert.assertTrue(validator.validate("$.as[?(@.name == 'samba')]"));
Assert.assertFalse(validator.validate("a['??kangaroo   \"A\"'][??(@.name == 'a')].value"));

References:

  1. https://goessner.net/articles/JsonPath/
  2. https://code.google.com/archive/p/jsonpath/
sidmishraw
  • 390
  • 4
  • 15