wanglingsong/JsonSurfer

[-1:] indexing seems to return wrong elements.

SpacRocket opened this issue · 4 comments

When trying to execute this snippet:

String json = "[1,2,3]";
Collector collector = SURFER.collector(json);
ValueBox<Collection<Object>> box = collector.collectAll("$[-1:]", Object.class);

Code returns [1,2,3], shouldn't it return element 3 according to JSONPath specification?
https://goessner.net/articles/JsonPath/

//book[last()]	$..book[(@.length-1)]
$..book[-1:]	the last book in order.

negative index is not supported yet

After looking into it, It seems like it's better for the code base to keep it without this functionality. I came up with:

Checking length of array and then converting to JsonPath with positive index.

Surfing Context compares all incoming node to the JsonPath required and then dispatching it to all listeners.
With this idea in principle library would need to traverse array two times, first to determine the size and then to dispatch.

Other libraries are able to do this because they are keeping the data in the memory but JSON Surfer is streaming.

exactly

I think maybe throwing an exception each time someone creates slice with negative index might be a good idea as It's not really a 'legal move' that now works by just printing entire array but this one probably would need to be released in major release as it could break some code for clients.

We could also just adapt documentation so it's clear.