json-path / JsonPath

Java JsonPath implementation
Apache License 2.0
8.92k stars 1.65k forks source link

Missing PathNotFoundException in nested arrays. #99

Open Jan539 opened 9 years ago

Jan539 commented 9 years ago

Hey, I got the following json

{
  "array1": [
    {
      "array2": []
    },
    {
      "array2": [
        {
          "key": "test_key",
        }
      ]
    }
  ]
}

And i want to read the following path : $.array1[*].array2[0].key. Actually my goal was to retrieve a list with [null, "test_key"] but this didnt work, however I expected at least a PathNotFoundException for $.array1[0].array2[0].key. Instead I get a list with ["test_key"].

greetings, jan

nztomas commented 9 years ago

+1

Exactly the same issue, I'm using Option.DEFAULT_PATH_LEAF_TO_NULL but the missing nodes are quietly ignored - I can see the null value only if the last leaf is missing.

kallestenflo commented 9 years ago

One thing that complicates this is the AS_PATH_LIST option. The results must be the same regardless if this option is set or not.

Configuration conf = Configuration.builder().build();

List<String> result = using(conf).parse(json).read("$.array1[*].array2[0].key");

assertThat(result).containsExactly("test_key");

vs

Configuration conf = Configuration.builder()
       .options(Option.AS_PATH_LIST).build();

List<String> result = using(conf).parse(json).read("$.array1[*].array2[0].key");

assertThat(result).containsExactly("$['array1'][1]['array2'][0]['key']");

If the first example was to return [null, "test_key"] how would this be represented in the path list?

zline commented 9 years ago

To get PathNotFoundException in this case (indefinite path + absent array indices) some option could be introduced: REQUIRE_PROPERTIES-like option, but more strict, e.g. REQUIRE_PATHS.

@nztomas Option.DEFAULT_PATH_LEAF_TO_NULL does not help you to get null because not a leaf but entire object node (at $['array1'][0]['array2'][0]) is missing.