首页 > 解决方案 > 如何使用 Karate JS 进行精确的复杂 JSON API 响应匹配

问题描述

假设这是我的 API 响应:

{
  "name": "hello-world",
  "listObjects": [
    {
      "id": 100,
    },
    {
      "id": 200,
    }
  ]
}

我希望通过以下响应来验证这一点:

{
  "name": "hello-world",
  "listObjects": [
    {
      "id": 100,
    },
    {
      "id": 200,
    }
  ]
}

为此,我正在做:response == myJson。这完美!

listObjects可以按任何顺序排列。有时响应可能是这样的:

  "name": "hello-world",
  "listObjects": [
    {
      "id": 200,
    },
    {
      "id": 100,
    }
  ]
}

在这种情况下,如何仅在一行中进行精确的 json 匹配?我不想进行单独的密钥匹配。它应该在一行中完成。

标签: cucumberkarate

解决方案


您至少需要 2 行。阅读文档以了解更多信息:

* def list = [{ id: 200 }, { id: 100 }]
* def response =
"""
{
  "name": "hello-world",
  "listObjects": [
    {
      "id": 100,
    },
    {
      "id": 200,
    }
  ]
}
"""
* match response.listObjects contains only list
* match response == { name: 'hello-world', listObjects: '#(^^list)' }

推荐阅读