wanglingsong / JsonSurfer

A streaming JsonPath processor in Java
MIT License
292 stars 55 forks source link

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

Closed SpacRocket closed 5 months ago

SpacRocket commented 8 months ago

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.
wanglingsong commented 8 months ago

negative index is not supported yet

SpacRocket commented 5 months ago

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.

wanglingsong commented 5 months ago

exactly

SpacRocket commented 5 months ago

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.