Skip to content

Slice Selector for reversing the Output  #176

Description

@MarkusMas

Many JsonPath methods like dchester and goessner feature reversing the output with the slice selector. For example:

Example Description
$[-1] Last item
$[-2:] Last two items
$[:-2] All items except the last two
$[::-1] All items, reversed
$[1::-1] First two items, reversed
$[:-3:-1] Last two items, reversed
$[-3::-1] All items except the last two, reversed

Source: https://danielaparker.github.io/JsonCons.Net/articles/JsonPath/JsonConsJsonPath.html

The slicing works great with JSONPath-Plus however reversing (with -1 at the end) seems to be unavailable.

Is it possible to add this feature. Or is there any othe workaroud. Maybe a different expression that is not documented?

Activity

  1. fabo-afpa commented on Jul 3, 2025

    @fabo-afpa

    For the last one, you can do $[(@.length-1)].

  2. MarkusMas commented on Jul 3, 2025

    @MarkusMas
    Author

    Hi @fabo-afpa,
    i solved my issue by reversing my json later in the code.

    however i just tried* your solution but doesn't seem to work. can you please share a full example with input json, query and expected output, please?

    *i have tried using this online query tester: https://www.jsonquerytool.com/

  3. fabo-afpa commented on Jul 3, 2025

    @fabo-afpa

    With the query tester you suggest, keep the JSON:

    {
        "key": "value",
        "array": [
            {
                "key": 1
            },
            {
                "key": 2,
                "dictionary": {
                    "a": "Apple",
                    "b": "Butterfly",
                    "c": "Cat",
                    "d": "Dog"
                }
            },
            {
                "key": 3
            }
        ]
    }
    

    Use

    $.array[(@.length-1)].key

    as Query, the Output should be:

    [ 3 ]

    I tried with all the Transform libs on the left.

  4. MarkusMas commented on Jul 3, 2025

    @MarkusMas
    Author

    Hi @fabo-afpa, thanks for the example.
    the output of your example is actually the last item of the json.
    I was looking for a solution to get the output reversed using the querytool. For example:

    {
      "d": "Dog",
      "c": "Cat",
      "b": "Butterfly",
      "a": "Apple"
    }
    

    From what i learned in the meantime i think this is not possible with the querytools. So i solved this in my following code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions