如何使用karate.set()在json中添加新密钥

时间:2018-07-05 06:13:01

标签: karate

嗨,我正尝试使用karate.set向json添加新的键和值,但由于无效的变量名称而无法正常工作,以下是我的代码:

Backgroung:
* def myjson = {name: 'test', start_date: '27-04-2017'}
* def localDateTime = Java.type("java.time.LocalDateTime").now()
Scenario:
 * string endDate = 'myjson.end_date'
 * def endDateTmp = karate.eval(endDate)
 * eval if (endDateTmp == null) karate.set(myjson,'$.end_date',localDateTime)

例外:

java.lang.RuntimeException: javascript evaluation failed: if (endDateTmp == null) karate.set(myjson,'$.end_date',localDateTime)
    at com.intuit.karate.ScriptBindings.eval(ScriptBindings.java:115)
    at com.intuit.karate.ScriptBindings.updateBindingsAndEval(ScriptBindings.java:103)
    at com.intuit.karate.ScriptBindings.evalInNashorn(ScriptBindings.java:88)
    at com.intuit.karate.Script.evalJsExpression(Script.java:362)
    at com.intuit.karate.StepDefs.eval(StepDefs.java:581)
Caused by: java.lang.RuntimeException: invalid variable name: {name:test, start_date:27-04-2017}
at com.intuit.karate.Script.validateVariableName(Script.java:553)
    at com.intuit.karate.Script.setValueByPath(Script.java:1480)
    at com.intuit.karate.Script.setValueByPath(Script.java:1455)
    at com.intuit.karate.ScriptBridge.set(ScriptBridge.java:101)
    at jdk.nashorn.internal.scripts.Script$23$\^eval\_.:program(<eval>:1)

如果密钥已经存在,那么尝试设置是可行的,请建议我如何使用karate.set()或其他任何方式添加新密钥。

谢谢。

1 个答案:

答案 0 :(得分:2)

我认为您需要更仔细地阅读空手道文档和示例,并且还应该了解一些JS概念。

* def myjson = { name: 'test', start_date: '27-04-2017' }
* def localDateTime = Java.type("java.time.LocalDateTime").now()
* eval if (!myjson.end_date) myjson.end_date = localDateTime + ''
* print myjson

这将导致:

[print] {
  "name": "test",
  "start_date": "27-04-2017",
  "end_date": "2018-07-05T18:13:07.547"
}

请注意,我通过串联将Java Date转换为String。我将介绍如何按照您希望作为家庭作业的方式正确格式化它。请参考此处的示例以获取一些提示:https://github.com/intuit/karate#java-interop