Mule 4 DataWeave 上的编译时错误
我是 Mulesoft Dataweave 语言的新手,我不明白我在下面的 code-1 和 code-2 语法中犯了什么错误。它在 if 块上显示编译时错误。你能建议我在下面的脚本中犯了什么错误吗?
代码 1
%dw 2.0
fun createUserData(name) = {
if(name=="USA"){
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
}else{
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
}
}
output application/json
---
createUserData("USA")
代码 2
output application/json
---
if(payload != null){
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
}else{
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
}
I am new for Mulesoft Dataweave language and I am not understanding what mistake I am doing in below both code-1 and code-2 syntax. It is showing a compile time error on the if blocks. Can you please suggest what mistake am I doing in below scripts?
Code-1
%dw 2.0
fun createUserData(name) = {
if(name=="USA"){
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
}else{
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
}
}
output application/json
---
createUserData("USA")
code-2
output application/json
---
if(payload != null){
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
}else{
readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题不在于条件,而在于它返回的对象的语法。在 DataWeave 中,大括号不是 if/else 条件的一部分。大括号界定一个对象,其中包含键值对。您的表达式启动了一个对象,但错过了键。假设 readUrl() 返回一个对象 { a: 1 } ,它将相当于:
这是无效的,因为外部对象没有键,只有一个值。在这种情况下,您可以只返回不带大括号的 readUrl() 的结果:
因为 if/else 的每个分支内的任何内容都只是更多表达式,您也可以转换它们。
有关更多示例,请参阅@Salim Khan 的答案。
Your problem is not with the condition but the syntax for the object it returns. In DataWeave curly braces are not part of the if/else condition. The curly braces delimit an object, which contains key-value pairs. Your expression starts an object but misses the keys. Assuming the readUrl() returns an object { a: 1 } it would be equivalent to:
which is invalid because the outer object has no keys, only a value. In that case you could just return the result of readUrl() without the braces:
Since whatever inside each branch of the if/else are just more expressions you can transform them too.
See @Salim Khan's answer for more examples.
您可以尝试使用这样的方法
另一个示例脚本:
另一个示例:
You can try with an approach like this
Another sample script:
Another sample: