PaesslerAG / jsonpath

BSD 3-Clause "New" or "Revised" License
172 stars 37 forks source link

Accessing arrays with string keys: #3

Closed maja42 closed 5 years ago

maja42 commented 6 years ago

When accessing arrays like this:

arr["0"]

... I expect jsonpath to return an error. Array-indices are always integer and never strings. Instead, I get the first element. Is this by design? If so, I find it counter-intuitive. Also, in combination to issue 2: https://github.com/PaesslerAG/jsonpath/issues/2, the following panics:

arr["-1"]

generikvault commented 5 years ago

Yes it is intended. Values will be converted if they don't have the expected type. This is also done in the base script language: https://github.com/PaesslerAG/gval

moshevi commented 5 years ago

Hi @generikvault Couldn't follow your answer regarding the string indices that are so because no expected value. Can you elaborate on that and provide a sample? Thanks.

generikvault commented 5 years ago

Hi @moshevi

it's basically the example from above. If you have an array, let's say $.myarray, and access an element of the array via a string selector $.myarray["1"] the string will be converted to an integer.

This will not work for unsupported map types like map[int]interface{}.

moshevi commented 5 years ago

Hi @generikvault So why can't I use $.myarray[1] instead of $.myarray["1"] ?

generikvault commented 5 years ago

$.myarray[1] works fine. The discussion was wether $.myarray["1"] should throw an array or convert the string to an integer.

Well and about the panic on negative indice but that is fixed.

moshevi commented 5 years ago

Hi @generikvault Sorry for misleading you....I meant that the returned paths from search expression (like: {#: $..[?(@.name == "Value")]} will be string indices and not numeric ones if the value is found inside an array.

generikvault commented 5 years ago

Ah yes. Placeholder (#, #0, #1, ...) have a static string type and yeah this is something I'm not absolutly sure about.