How to find last element in Array list using jsonpath expression?

Pradeep Poojari picture Pradeep Poojari · Aug 22, 2015 · Viewed 11.8k times · Source

I have json string like below

[
    {
        "topic": "inputTopic",
        "key": "0",
        "message": "test",
        "partition": 0,
        "offset": 0
    },
    {
        "topic": "inputTopic",
        "key": "0",
        "message": "test",
        "partition": 0,
        "offset": 1
    },
    {
        "topic": "inputTopic",
        "key": "0",
        "message": "test",
        "partition": 0,
        "offset": 2
    },
    {
        "topic": "inputTopic",
        "key": "0",
        "message": "test",
        "partition": 0,
        "offset": 3
    },
    {
        "topic": "inputTopic",
        "key": "0",
        "message": "test",
        "partition": 0,
        "offset": 4
    },
    {
        "topic": "inputTopic",
        "key": "0",
        "message": "test",
        "partition": 0,
        "offset": 5
    },
    {
        "topic": "inputTopic",
        "key": "0",
        "message": "test",
        "partition": 0,
        "offset": 6
    },
    {
        "topic": "inputTopic",
        "key": "0",
        "message": "Hi Test",
        "partition": 0,
        "offset": 7
    },
    {
        "topic": "inputTopic",
        "key": "0",
        "message": "Hi Test",
        "partition": 0,
        "offset": 8
    },
    {
        "topic": "inputTopic",
        "key": "0",
        "message": "Hi Test",
        "partition": 0,
        "offset": 9
    }
]

How can I get last item using jsonpath expression?

 {
    "topic": "inputTopic",
    "key": "0",
    "message": "Hi Test",
    "partition": 0,
    "offset": 9
}

Answer

Mario Eis picture Mario Eis · Jul 11, 2017

As you can read in the docs you can ether do a

$..book[(@.length-1)]

as mentioned by Duncan above. Or you can

$..book[-1:]

Personally I find the first a bit more expressive, the latter a bit smarter to write. The latter also seems to be the intended default. I'd say it's a question of personal flavor.