[英]How to generate JSON with N objects in array using Karate framework?
I have next json object:我有下一个 json 对象:
{
"email": "api.test@cool.io",
"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:我想把它放在名为“udpated”的数组中 N 次:
{ 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我试过这样的纯 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
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": "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"
}
}
See if this makes sense.看看这是否有意义。 Yes there is an annoying edge case bug for JS nested arrays coming back as JSON (Map-s).
是的,JS 嵌套数组作为 JSON (Map-s) 返回有一个令人讨厌的边缘情况错误。 There is a quick fix solution that you can find in the comments here: https://stackoverflow.com/a/54256766/143475
您可以在此处的评论中找到快速修复解决方案: 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.只需将空手道世界中的任何内容视为 Java(更喜欢这个),将 JS 函数中的任何内容视为纯 JS - 但可以引用现有的 Java 风格变量。 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. copy
摆脱了正确序列化的重复对象引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.