空手道:我可以迭代一个Json数组响应并做一些条件语句 [英] Karate: Can I iterate on a Json array response and do some conditional statements

查看:66
本文介绍了空手道:我可以迭代一个Json数组响应并做一些条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的json数组响应如下:

My json array response is something like below:

response = [
{
"ID": "123",
"Name":"Test1",
"Data":{
      "Status":"Red",
      "Message":"user not valid",
      "Code": "ERROR-P1"
      }
},
{
"ID": "143",
"Name":"Test2",
"Data":{
      "Status":"Amber",
      "Message":"user data missing",
      "Code": "ERROR-P2"
      }
},
{
"ID": "133",
"Name":"Test3",
"Data":{
      "Status":"Green",
      "Message":"",
      "Code": ""
      }
}

在json数组中可能会有更多具有相同数据和状态的条目。
我的用例是基于以下条件进行检查:如果我的json数组的状态为红色或琥珀色,则消息和代码不为空,类似地,如果我的状态为绿色,则消息和代码为空。
我需要遍历整个数组并验证这种情况。
并且还需要从Array Json响应中获取状态计数:红色,琥珀色和绿色。
空手道可能是最好的解决方案?
任何帮助将不胜感激。
谢谢

There could be more entries in the json array with same data and status. My use case is to check, based on a condition that if my json array has Status as Red or Amber, then message and code is not empty and similarly if my status is Green then message and code is empty. I need to iterate to the entire array and validate this scenario. And also need to get a count of Status: Red, Amber and Greens from the Array Json response. What could be the best possible solution with karate? Any help would be appreciated. Thank you

推荐答案

在这里您要去:

* def red = []
* def amber = []
* def green = []
* def fun = 
"""
function(x){ 
  if (x.Data.Status == 'Red') karate.appendTo(red, x);
  if (x.Data.Status == 'Amber') karate.appendTo(amber, x);
  if (x.Data.Status == 'Green') karate.appendTo(green, x);
}
"""
* karate.forEach(response, fun)
* assert red.length == 1
* match each red..Message == 'user not valid'
* match each amber contains { Data: { Status: 'Amber', Message: 'user data missing', Code: 'ERROR-P2' } }

这篇关于空手道:我可以迭代一个Json数组响应并做一些条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆