使用 groovy 通过 Json 响应的子子值获取父元素的 id
Get the id of a parent element by a sub-child value of Json response using groovy
我有以下 groovy 脚本来从响应中获取值。
import com.eviware.soapui.support.XmlHolder
import groovy.json.JsonSlurper
def response = context.expand( '${GetLoansList#Response}' ).toString()
log.info(response)
def slurper = new JsonSlurper()
def json = slurper.parseText response
log.info(json.items.id)
我的 json 回复与此类似
{
"items" : [
{
"id" : 48223,
"name" : "LAI-00151007",
"amount" : 25050.0,
"interest_rate" : 25.99,
"term" : 60,
},
{
"id" : 48262,
"name" : "LAI-00152581",
"amount" : 44225.0,
"interest_rate" : 18.9,
"term" : 36,
},
],
"total_count" : 13
}
我想得到给定名字对应的 'id' ("name": "LAI-00152581")。做这个的最好方式是什么?谢谢
您可以使用:
json.items.find({ it.name == "LAI-00152581" })?.id
?.
是为了安全,没有items
符合条件。在这种情况下,结果将是 null
从 Groovy 2.5.0 开始,还有一种方法可以做到这一点,这在语义上是等价的:
json.items.findResult { if (it.name == "LAI-00152581") return it.id }
我有以下 groovy 脚本来从响应中获取值。
import com.eviware.soapui.support.XmlHolder
import groovy.json.JsonSlurper
def response = context.expand( '${GetLoansList#Response}' ).toString()
log.info(response)
def slurper = new JsonSlurper()
def json = slurper.parseText response
log.info(json.items.id)
我的 json 回复与此类似
{
"items" : [
{
"id" : 48223,
"name" : "LAI-00151007",
"amount" : 25050.0,
"interest_rate" : 25.99,
"term" : 60,
},
{
"id" : 48262,
"name" : "LAI-00152581",
"amount" : 44225.0,
"interest_rate" : 18.9,
"term" : 36,
},
],
"total_count" : 13
}
我想得到给定名字对应的 'id' ("name": "LAI-00152581")。做这个的最好方式是什么?谢谢
您可以使用:
json.items.find({ it.name == "LAI-00152581" })?.id
?.
是为了安全,没有items
符合条件。在这种情况下,结果将是 null
从 Groovy 2.5.0 开始,还有一种方法可以做到这一点,这在语义上是等价的:
json.items.findResult { if (it.name == "LAI-00152581") return it.id }