我可以在 JSON 个对象上使用 ## 操作吗?

Can I use the ## operation on JSON objects?

查看文档可以很直接地了解如何在字段上使用 ## 运算符,例如

<pre><code>* def data = { a: 'hello', b: null, c: null } * def json = { foo: '#(data.a)', bar: '#(data.b)', baz: '##(data.c)' } * match json == { foo: 'hello', bar: null }

但是如果我想在没有属性的 json 对象上使用它怎么办?例如。如果我正在做类似

的事情 <pre><code>* def data = { a: 'hello', b: null, c: null } * def json = { foo: '#(data.a)', bar: '#(data.b)', jsonObject: {baz: '##(data.c)'} } * match json == { foo: 'hello', bar: null }

抱怨有一个空对象 </p> <pre><code>actual: {foo=hello, bar=null, jsonObject={}}, expected: {foo=hello, bar=null}

并将 ##{baz: '##(data.c)'} 或 ##({baz: '##(data.c)'}) 作为 json对象值不起作用,因为 ## 未被正确识别。

正确的语法是什么?或者有其他方法可以实现我所描述的内容吗?

这实际上是一个有点复杂的条件替换。方法如下:

* def data = { a: 'hello', b: null, c: null }
* def temp = data.c ? { baz: data.c } : null
* def json = { foo: '#(data.a)', bar: '#(data.b)', jsonObject: '##(temp)' }
* match json == { foo: 'hello', bar: null }

也许你把事情搞得太复杂了,你需要的是:

* def data = { a: 'hello', b: null, c: null }
* def json = { foo: '#(data.a)', bar: '#(data.b)' }
* if (data.c) json.jsonObject = ({ baz: data.c })
* match json == { foo: 'hello', bar: null }