首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我可以在JSON对象上使用##操作吗?

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

Stack Overflow用户
提问于 2021-07-22 17:42:00
回答 1查看 25关注 0票数 1

查看文档,很容易就知道如何在字段上使用##运算符

代码语言:javascript
运行
复制
* 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对象上使用它呢?例如,如果我正在做像这样的事情

代码语言:javascript
运行
复制
* 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 }

它抱怨有一个空的对象

代码语言:javascript
运行
复制
actual: {foo=hello, bar=null, jsonObject={}}, expected: {foo=hello, bar=null}

并且将##{baz:' ## (data.c)'}或##({baz:'##(data.c)'})作为jsonObject值不起作用,因为无法正确识别##。

正确的语法是什么?或者有没有其他方法来做我所描述的事情?

EN

Stack Overflow用户

回答已采纳

发布于 2021-07-22 18:41:07

这实际上是一个有点复杂的条件替换。下面是你怎么做的:

代码语言:javascript
运行
复制
* 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 }

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

代码语言:javascript
运行
复制
* 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 }
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68482628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档