0

I need to validate whether the below json-paths are syntactically correct or not:

$[*].key1.key2[*].key3.key4 // valid
$[*].key1/key2[*].key3"key4 // invalid

Is there any API which can check the above json-path expressions and return true/false in Java ?

TheCodeCache
  • 820
  • 1
  • 7
  • 27

2 Answers2

1

Try importing Jayway JsonPath https://github.com/json-path/JsonPath then JsonPath.read("{}", yourJsonPath); and if it doesn't explode the path is valid.

  • sure, will try this and get back, thanks @Satish – TheCodeCache Aug 11 '20 at 12:59
  • If you think this is helpful then please vote up!! – Satish Hawalppagol Aug 11 '20 at 14:21
  • 1
    sure will vote up, I guess your soln should work, but I've not yet tried so let me try this up and then if it works will accept the answer – TheCodeCache Aug 11 '20 at 15:25
  • 19:19:54.644 [main] DEBUG c.j.j.internal.path.CompiledPath - Evaluating path: $['id'] Exception in thread "main" com.jayway.jsonpath.PathNotFoundException: No results for path: $['id'] at com.jayway.jsonpath.internal.path.EvaluationContextImpl.getValue(EvaluationContextImpl.java:133) at com.jayway.jsonpath.JsonPath.read(JsonPath.java:187) at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:102) at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:89) at com.jayway.jsonpath.JsonPath.read(JsonPath.java:502) – TheCodeCache Aug 12 '20 at 13:58
  • Hi @Satish, it threw the above expcetion with your suggested code-piece, however, I tried around the other supported api and found exact api for my question which is JsonPath.compile(yourJsonPath), but since I got a hint from your suggestion so have upvoted, thanks for the hint/answer, keep guiding – TheCodeCache Aug 12 '20 at 14:10
  • I've given an edit with your answer updated with my findings, if it is accepted by SO then will accept your answer as well, thanks – TheCodeCache Aug 12 '20 at 14:24
  • @Manoranjan use try catch block as provided in 1st solution – Satish Hawalppagol Aug 13 '20 at 02:29
-1

Use a JSON parser like JSON.parse:

function IsJsonString(str) 
  {
      try 
      {
        JSON.parse(str);
      }
      catch (e) 
      {
        return false;
      }
    return true;
  }