Pradeep Poojari
Pradeep Poojari

Reputation: 165

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

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
}

Upvotes: 15

Views: 28331

Answers (3)

vlatko606
vlatko606

Reputation: 1149

What was working here for me was:

$..[-1:]

enter image description here

You can test it here: https://jsonpath.com/

Upvotes: 3

Mario Eis
Mario Eis

Reputation: 2901

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.

Upvotes: 36

Duncan
Duncan

Reputation: 841

You can use the underlying language features when using JsonPath, so in JavaScript for example, the length property is available. You can therefore say I want the last one by asking for length minus one.

Assuming you are using JsonPath from JavaScript the following query will find the last item:

$.[(@.length-1)]

You can see the query working here on this online JsonPath tester: http://www.jsonquerytool.com/sample/jsonpathlastinarray

Upvotes: 10

Related Questions