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
}
I'd say it's a question of personal flavor. Even more convenient is "$..book [-1]" which returns just the last element, whereas "$..book [-1:]" returns an array containing the last element. You can use the underlying language features when using JsonPath, so in JavaScript for example, the length property is available.
We can extract multiple items from the array at different indexes. The syntax to do so is [i,j,k..]. For e.g. to extract the first 2 array items we will write the JSONPath as For the JsonPath shown below, we will change our Json to have more nodes.
In this tutorial, we will suggest three methods of getting the last item in a JavaScript Array. The first method for getting the last item is the length property. You can pick the last item by doing the following: Watch a video course JavaScript - The Complete Guide (Beginner + Advanced) Another succinct method is used.
Array slice operator is wonderful operator to extract selected items from Json. Taking the example of books, what if we want to retrieve every alternative book in the Json. To do that we will need the Array, Slice operator. Syntax of Array Slice operator is [StartIndex : EndIndex : Steps].
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With