1

I'd like to find all Json paths from a json file where attribute type is primitive (not object or array)

Consider jsonString:

{
   "header": {
       "version": 2,
       "original": "ori",
       "parent": "par",
       "eventId": 11,
       "correlation": "uuid",
       "timestamp": "03.04.2020",
       "local": true,
       "location": {
           "facility": {
               "id": 3,
               "type": "en"
           }
       }
   },
   "body": {
       "field": 3
   }
} 

I use the following code:

Configuration configuration = Configuration.builder().options(Option.AS_PATH_LIST).build();
List<String> paths = JsonPath.using(configuration).parse(jsonString).read("$..*");

ACTUAL RESULT: Pattern "$..*" returns me all the paths present in the json:

  • $['header']
  • $['body']
  • $['header']['version']
  • $['header']['original']
  • $['header']['parent']
  • $['header']['eventId']
  • $['header']['correlation']
  • $['header']['timestamp']
  • $['header']['local']
  • $['header']['location']
  • $['header']['location']['facility']
  • $['header']['location']['facility']['id']
  • $['header']['location']['facility']['type']
  • $['body']['field']

EXPECTED RESULT: I need to get only these ones:

  • $['header']['version']
  • $['header']['original']
  • $['header']['parent']
  • $['header']['eventId']
  • $['header']['correlation']
  • $['header']['timestamp']
  • $['header']['local']
  • $['header']['location']['facility']['id']
  • $['header']['location']['facility']['type']
  • $['body']['field']

The Filter should be generic so it can resolve any json format given as input.

Serhii Kachan
  • 345
  • 4
  • 13

1 Answers1

0

You can use the below JSONPath that will give the path that have objects or array, which you can then exclude from the entire list of JSONPath.

JSONPath

$..*[?(@.length != 0)]

Java Code

List<String> allPaths = JsonPath.using(configuration).parse(jsonString).read("$..*");
List<String> exludedPaths = JsonPath.using(configuration).parse(jsonString).read("$..*[?(@.length != 0)]");
List<String> primitivePaths = allPaths.removeAll(exludedPaths);
Akshay G
  • 2,070
  • 1
  • 15
  • 33