Reputation: 231
Hi i am trying to add new key and value to json using karate.set but its not working getting exception as invalid varibale name, below is my code:
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)
Exception:
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)
If key already exist then trying to set is working, please suggest me how to add new key using karate.set() or any other way to do it.
Thanks in advance.
Upvotes: 2
Views: 7675
Reputation: 58058
I think you need to read through the Karate documentation and examples a little more carefully and also be clear about some JS concepts.
* def myjson = { name: 'test', start_date: '27-04-2017' }
* def localDateTime = Java.type("java.time.LocalDateTime").now()
* if (!myjson.end_date) myjson.end_date = localDateTime + ''
* print myjson
Which results in:
[print] {
"name": "test",
"start_date": "27-04-2017",
"end_date": "2018-07-05T18:13:07.547"
}
Note that I converted the Java Date to a String via concatenation. I leave how to format it correctly the way you want as a homework for you. Refer the example here for some hints: https://github.com/intuit/karate#java-interop
Upvotes: 3