'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?



Solution 1:[1]

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"]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aspok