1

从下面的 JSON 中,我正在尝试编写一个 Gpath,它只会在“type”字段等于ride_state时返回“state”字段(即我只想要两个“open”状态)

[{
    "type": "day",
    "data": {
        "id": "7a46a975-5474-4278-a56f-4deadd9a276d",
        "state": "closed"
    }
}, {
    "type": "ride_state",
    "data": {
        "id": "13f3b625-b39e-4875-b29c-0173712b3c87",
        "state": "open"
    }
}, {
"type": "ride_state",
    "data": {
        "id": "b52b5081-e1df-42da-ba76-027c63205f8e",
        "state": "open"
     }
}]

我是 Groovy 和 Gpath 的新手,到目前为止还没有找到方法来做到这一点,有人可以帮忙吗?

4

1 回答 1

0

With a valid json, this can be done as below:

def jsonString = """
[{
    "type": "day",
    "data": {
        "id": "7a46a975-5474-4278-a56f-4deadd9a276d",
        "state": "closed"
    }
}, {
    "type": "ride_state",
    "data": {
        "id": "13f3b625-b39e-4875-b29c-0173712b3c87",
        "state": "open"
    }
}, {
    "type": "ride_state",
    "data": {
        "id": "b52b5081-e1df-42da-ba76-027c63205f8e",
        "state": "open"
    }
}]
"""

assert new groovy.json.JsonSlurper()
                      .parseText( jsonString )
                      .findResults {it.type == 'ride_state' ? it.data.state : null} == 
                      ['open', 'open']
于 2015-04-22T14:42:44.490 回答