首页 > 解决方案 > 空手道 - 从 json 中选择一个随机元素

问题描述

每次运行代码时,我都需要从下面的示例 json 中选择任何随机值。我怎样才能在空手道中做到这一点?我需要获取任何随机值并在另一个功能文件中使用。

def myJson = 
"""
{
      "sampleJson": {
        "random1": "1",
        "random2": "2",
        "random3": "3",
        "random4": "4",
        "random5": "5"
      }
  }
"""

标签: karate

解决方案


另请参阅:https ://github.com/intuit/karate#commonly-needed-utilities

* def random = function(max){ return Math.floor(Math.random() * max) + 1 }
* def myJson = 
"""
{
  "sampleJson": {
    "random1": "1",
    "random2": "2",
    "random3": "3",
    "random4": "4",
    "random5": "5"
  }
}
"""
* def key = 'random' + random(5)
* def result = myJson.sampleJson[key]
* print result

另见:https ://stackoverflow.com/a/70376593/143475


推荐阅读