【问题标题】:Delete JSON object properties with JavaScript in Karate在空手道中使用 JavaScript 删除 JSON 对象属性
【发布时间】:2018-12-07 05:53:14
【问题描述】:

如何动态删除 JSON 对象属性?我试过这个:

* def delKey = 
                    """
                              function(json, key) {
                                delete json[key];
                                return json;
                              }
                    """

* def aJson = { row: null, age: 35 , city: 'na'}
* print "Before: "
* print aJson
* def called = delKey(aJson, 'age')
* print "After: "
* print aJson

结果:

【问题讨论】:

    标签: json object dynamic properties karate


    【解决方案1】:

    我想你还没有看到removeset 关键字。这是正确的方法。还要注意print 语句如何支持逗号分隔的样式,以便它可以漂亮地打印:

    * def aJson = { row: null, age: 35 , city: 'na' }
    * print 'Before: ', aJson
    * remove aJson.age
    * print 'After: ', aJson
    

    如果需要动态删除key,可以使用JS APIkarate.remove(name, path)。参考文档!

    【讨论】:

    • 感谢您的回复。我真的阅读文档仔细。 removeset 对我的情况没有帮助,但 eval karate.remove... 有帮助。尽管如此,问题仍然存在 - 为什么上面的代码不起作用?
    • @DragomirDraganov 谢谢,我实际上仔细看了看。由于空手道的工作方式,变量是功能块中的 Java Map 对象。所以只需将函数的第二行更改为 json.remove(key); 即可!
    • @PeterThomas 我可以在 if 条件下调用此删除吗?下面的代码给了我语法错误 * if(condition=="true"){remove aJson.age} >>>> js failed: 01: if(condition=="true"){remove aJson.age}
    • @SourabhRoy 在 1.X 版本中尝试使用 delete 而不是 remove。否则问一个新问题
    • 非常感谢@PeterThomas
    猜你喜欢
    • 2011-01-16
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    相关资源
    最近更新 更多