如何使用jsonpath表达式在Array列表中查找最后一个元素?

Pra*_*ari 4 jsonpath

我有像下面的json字符串

[
    {
        "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
    }
]
Run Code Online (Sandbox Code Playgroud)

如何使用jsonpath表达式获取最后一项?

 {
    "topic": "inputTopic",
    "key": "0",
    "message": "Hi Test",
    "partition": 0,
    "offset": 9
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*Eis 11

正如你可以在文档中阅读的那样,你可以做一个

$..book[(@.length-1)]
Run Code Online (Sandbox Code Playgroud)

正如Duncan上面提到的那样.或者你可以

$..book[-1:]
Run Code Online (Sandbox Code Playgroud)

我个人认为第一个更有表现力,后者更聪明一点.后者似乎也是预期的默认值.我会说这是个人风味的问题.

  • 更方便的是“$..book[-1]”,它仅返回最后一个元素,而“$..book[-1:]”返回包含最后一个元素的数组。 (3认同)

Dun*_*can 5

您可以在使用JsonPath时使用基础语言功能,因此在JavaScript中,长度属性可用.因此,您可以通过要求长度减去1来说我想要最后一个.

假设您正在使用JavaScript中的JsonPath,以下查询将找到最后一项:

$.[(@.length-1)]
Run Code Online (Sandbox Code Playgroud)

你可以在这个在线JsonPath测试器上看到这里的查询:http://www.jsonquerytool.com/sample/jsonpathlastinarray