Denis
Denis

Reputation: 49

How to generate JSON with N objects in array using Karate framework?

I have next json object:

{
  "email": "[email protected]",
  "firstName": "John",
  "lastName": "Doe",
  "birthday": "1982-08-30",
  "createdAt": "2015-10-02T08:23:53Z",
  "gender": "male",
  "businessUnit": "DE"
}

And I want put it in my array named "udpated" N times:

{ updated : [], deleted : []}

Would you be so kind to tell how could I do this using Karate framework? How that might be done in elegant way?

I have tried pure JS like this

 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

but got as a result not an Array but a Map. Here is my result :

15:58:45.580 [main] INFO  com.intuit.karate - [print] {
  "updated": {
    "0": {
      "email": "[email protected]",
      "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"
  }
}

Upvotes: 1

Views: 5017

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58058

See if this makes sense. Yes there is an annoying edge case bug for JS nested arrays coming back as JSON (Map-s). There is a quick fix solution that you can find in the comments here: https://stackoverflow.com/a/54256766/143475

Just think of anything in the Karate world as Java (prefer this) and anything within a JS function as pure JS - but which can refer to an existing Java-flavoured variable. There are multiple elegant ways to do this - but this is what I came up with quickly.

* 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

The copy gets rid of the duplicate object reference getting serialized properly.

Upvotes: 1

Related Questions