根据条件从响应中获取值,并将其存储到变量

发布于 2025-02-08 23:36:08 字数 815 浏览 1 评论 0原文

我想根据条件从响应中获取值,然后将其存储到变量中。

在下面的JSON中,当名称与我喜欢的东西匹配时,我想存储该值。有没有方法可以使用空手道API实现这一目标?

{
  "results": [
    {
      "name": "Sample1",
      "email": "[email protected]",
      "id": "U-123"
    },
    {
      "name": "Sample2",
      "email": "[email protected]",
      "id": "U-456"
    },
    {
      "name": "Sample3",
      "email": "[email protected]",
      "id": "U-789"
    }
  ]
}

I would like to get the value from the response based on a condition and store it to a variable.

In the below JSON, I would like to store the value when the name matches to something I prefer. Is there a way to achieve this using Karate API?

{
  "results": [
    {
      "name": "Sample1",
      "email": "[email protected]",
      "id": "U-123"
    },
    {
      "name": "Sample2",
      "email": "[email protected]",
      "id": "U-456"
    },
    {
      "name": "Sample3",
      "email": "[email protected]",
      "id": "U-789"
    }
  ]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦开始←不甜 2025-02-15 23:36:08

因此,在阅读评论后,我的解释是“查找” id其中namesample2。简单,只需使用filter()操作,请参阅文档: https ://github.com/karatelabs/karate#jsonpath-filters

find> find> find()方法作为非常简洁的示例

* def response =
"""
{ "results": [
    { "name": "Sample1", "email": "[email protected]", "id": "U-123" },
    { "name": "Sample2", "email": "[email protected]", "id": "U-456" },
    { "name": "Sample3", "email": "[email protected]", "id": "U-789" }
  ]
}
"""
* def id = response.results.find(x => x.name == 'Sample2').id
* match id == 'U-456'

而不是使用过滤器,而是使用JS Array 一些时间了解其工作原理。与知道JS的人交谈。

So after reading the comment, my interpretation is to "find" the id where name is Sample2. Easy, just use a filter() operation, refer the docs: https://github.com/karatelabs/karate#jsonpath-filters

Instead of using a filter, I'm using the JS Array find() method as a very concise example below:

* def response =
"""
{ "results": [
    { "name": "Sample1", "email": "[email protected]", "id": "U-123" },
    { "name": "Sample2", "email": "[email protected]", "id": "U-456" },
    { "name": "Sample3", "email": "[email protected]", "id": "U-789" }
  ]
}
"""
* def id = response.results.find(x => x.name == 'Sample2').id
* match id == 'U-456'

Take some time to understand how it works. Talk to someone who knows JS if needed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文