jacaaa
jacaaa

Reputation: 23

Groovy - access element of json

I have this json output:


{"UT":{
  "test_results":[
   [
     {
         "branches": "8",
          "build": "normal"
     },
     {
         "branches": "8",
         "build": "normal"
     }
   ]
  ],
 }
}

I use this piece of code:

            def json = JsonOutput.toJson(br2)
            def parsed = new groovy.json.JsonSlurper().parseText(json)

I parse the text but how could I access the values of build?

Upvotes: 0

Views: 266

Answers (1)

aspok
aspok

Reputation: 295

The JsonSlurper().parseText(json) call will return a LazyMap. From there, you can interact with it as you would with any map. The offcial groovy docs have an approachable explainer here.

In your case, there are multiple ways to get the values of build. Your json structure seems to have an extra list wrapping the test_results objects. If this is constant, you can do something like:

assert parsed["UT"]["test_results"][0]["branches"] == ["8", "8"]

alternatively, you can simply flatten the values returned by direct access:

assert parsed["UT"]["test_results"]["branches"].flatten() == ["8", "8"]

Upvotes: 1

Related Questions