简体   繁体   English

Groovy - json 的访问元素

[英]Groovy - access element of json

I have this json output:我有这个 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?我解析了文本,但如何访问构建的值?

The JsonSlurper().parseText(json) call will return a LazyMap. JsonSlurper().parseText(json)调用将返回一个 LazyMap。 From there, you can interact with it as you would with any map. The offcial groovy docs have an approachable explainer here .从那里,您可以像与任何 map 进行交互一样与它交互。官方 groovy 文档在此处有一个平易近人的解释器。

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.您的 json 结构似乎有一个额外的列表来包装test_results对象。 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"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM