热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在SoapUI中使用groovy脚本获取数组编号?-HowtogetarraynumberwithgroovyscriptinSoapUI?

IwanttoassertthevalueofapropertyinJsonresponsewiththeuseofGroovyscriptinSoapUI.I

I want to assert the value of a property in Json response with the use of Groovy script in SoapUI. I know a value for name but I need to know on which position the id is.

我想在SoapUI中使用Groovy脚本断言Json响应中的属性值。我知道名称的值,但我需要知道id的位置。

json response example:

json响应示例:

{  
   "names":[  
      {  
         "id":1,
         "name":"Ted"
      },
      {  
         "id":2,
         "name":"Ray"
      },
      {  
         "id":3,
         "name":"Kev"
      }
   ]
}

Let's say I know that there is a name Ray, I want the position and the id (names[1].id)

假设我知道有一个名字Ray,我想要的位置和id(名称[1] .id)

1 个解决方案

#1


1  

Here is the script to find the same:

这是找到相同的脚本:

import groovy.json.*
//Using the fixed json to explain how you can retrive the data
//Of couse, you can also use dynamic value that you get 
def respOnse= '''{"names": [ { "id": 1, "name": "Ted", }, { "id": 2, "name": "Ray", }, { "id": 3, "name": "Kev", } ]}'''
//Parse the json string and get the names
def names = new JsonSlurper().parseText(response).names
//retrive the id value when name is Ray 
def rayId = names.find{it.name == 'Ray'}.id
log.info "Id of Ray is : ${rayId}"

//Another way to get both position and id
names.eachWithIndex { element, index ->
  if (element.name == 'Ray') {
    log.info "Position : $index, And Id is : ${element.id}"
  }
}

You can see here the output

你可以在这里看到输出

enter image description here


推荐阅读
author-avatar
妞妞盼寒假_197
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有