1

From the JSON below, I am trying to write a Gpath that will only return the "state" field when the "type" field is equal to ride_state (i.e. I just want the two "open" states)

[{
    "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"
     }
}]

I am new to Groovy and Gpath and so far haven't been able to find a way to do this, could anyone please help?

dmahapatro
  • 49,365
  • 7
  • 88
  • 117
JamesWillett
  • 980
  • 2
  • 8
  • 20

1 Answers1

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']
dmahapatro
  • 49,365
  • 7
  • 88
  • 117