Properly validate JSON Path in Java

Viewed 37

I am looking for the good Java way to validate a JSON Path. However, it seems that everyone has its own definition of a "valid JSON Path". I'll explain myself.

In this post, I will consider the three following paths :

  1. field.innerField
  2. field.inner field
  3. field/innerField

I want to help my users to clearly understand if their JSON Paths are valid or not, and why. To do so, I want to validate the given paths, and if it is not valid, send them a link to the JSON Path documentation (https://jsonpath.com/)

I use 3 distinct "tools" to test the validation of these paths.

  • In my code, I use the compile function found in this class: com.jayway.jsonpath.JsonPath
  • I am using IntelliJ as an IDE, and when I use a String as a JsonPath, IntelliJ (somehow) check that my String is a valid JsonPath and add a red underline if the JsonPath is not valid
  • I validate my JsonPath online on https://jsonpath.com/

So for the first JSON Path it is okay, every tool agrees, the path is valid.

For the second path :

  • The compile function of JsonPath throws the following error InvalidPathException: Use bracket notion ['my prop'] if your property contains blank characters
  • In the same way, IntelliJ tell me that the path is not valid ((', '.', '..', <*> or '[' expected on the space character)
  • The online tool on jsonpath.com handle properly this path and retrieves the wanted elements

I am ok with my code throwing an error and expecting a more correct path (field.['inner field']), but my users will get lost by seeing that their paths work properly on the online editor.

For the third path :

  • The compile function of JsonPath do not throw any exception (but, the "real" JSON Path in this case is $.['field/innerField'], probably not was the user wanted.
  • However, IntelliJ tell me that the path is not valid ('(', '.', '..', <*> or '[' expected, got '/' on the / character)
  • The online editor on jsonpath.com has the same behavior as the compile function

If my users specify this path, they probably want in reality to use this JSON Path : $.field.innerField. So I would like to be able to detect if I am in this case (which IntelliJ editor somehow manage to do) and link them the documentation.

So in the end, I am looking for a validation method that will throw an exception in case 2 and 3, and an online documentation/editor that will behave accordingly. Does theses exists ? (And why everyone has his own way to do JSON Path :'( )

0 Answers
Related