如何使用Karate框架在数组中的N个对象中生成JSON?

时间:2019-04-12 13:36:25

标签: json karate

我有下一个json对象:

{
  "email": "api.test@cool.io",
  "firstName": "John",
  "lastName": "Doe",
  "birthday": "1982-08-30",
  "createdAt": "2015-10-02T08:23:53Z",
  "gender": "male",
  "businessUnit": "DE"
}

我想将它放在名为“ udpated”的数组中N次:

{ updated : [], deleted : []}

您是否愿意告诉我如何使用Karate框架执行此操作?怎么可能以优雅的方式完成?

我已经尝试过像这样的纯JS

 Scenario: read json within a js function1
        * def getId = function(){ return java.util.UUID.randomUUID() + '' }
        * def x = read('classpath:data/user.json')
        * eval
        """
         var body = { updated : [], deleted : []};
         var foo = function(){
            var uuid = getId();
            x.id = uuid;
            x.email = 'api.test+' + uuid + '@cool.io';
            body.updated.push(x);
            body.updated.push(x);
          }
          foo();
          karate.set('temp', body);
        """
        * print temp

,但结果不是数组而是Map。这是我的结果:

15:58:45.580 [main] INFO  com.intuit.karate - [print] {
  "updated": {
    "0": {
      "email": "api.test+543d3448-7726-4bb3-8762-e593fb2c5435@cool.io",
      "firstName": "John",
      "lastName": "Doe",
      "birthday": "1982-08-30",
      "createdAt": "2015-10-02T08:23:53Z",
      "gender": "male",
      "businessUnit": "DE",
      "id": "543d3448-7726-4bb3-8762-e593fb2c5435"
    }
  },
  "deleted": {
    "0": "#ref:java.util.LinkedHashMap"
  }
}

1 个答案:

答案 0 :(得分:1)

看看这是否有意义。是的,对于JS嵌套数组,它以JSON(Map-s)的形式存在一个烦人的边缘案例错误。您可以在以下注释中找到一种快速修复解决方案:https://stackoverflow.com/a/54256766/143475

只需将空手道世界中的任何内容都视为Java(更喜欢将其视为),并将JS函数中的任何内容都视为纯JS-但它们可以引用现有的Java风格的变量。有多种优雅的方法可以做到这一点-但这就是我很快想到的。

* def getId = function(){ return java.util.UUID.randomUUID() + '' }
* def x = { foo: 'bar' }
* def body = { updated : [], deleted : [] };
* def fun =
"""
function() {
  var uuid = getId();
  x.id = uuid;
  x.email = 'api.test+' + uuid + '@cool.io';
  body.updated.add(x);
  body.deleted.add(x);
}
"""
* eval fun()
* copy body = body
* print body

copy删除了正确序列化的重复对象引用。