14

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
}
Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37
Pradeep Poojari
  • 155
  • 1
  • 1
  • 9

3 Answers3

32

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.

Mario Eis
  • 2,724
  • 31
  • 32
  • 3
    Even more convenient is "$..book[-1]" which returns just the last element, whereas "$..book[-1:]" returns an array containing the last element. – Don Ho Mar 01 '21 at 18:28
9

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

Duncan
  • 781
  • 6
  • 7
2

What was working here for me was:

$..[-1:]

enter image description here

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

vlatko606
  • 909
  • 1
  • 13
  • 21