在 Dataweave 2 中有一种(简单的)方法可以将有效负载中的字符串字段转换为数字(如果是数字)和布尔值(如果是布尔值)
In Dataweave 2 is there a (simple) way to convert String fields in a payload to Numbers (if numbers) and Booleans (if booleans)
我最大的障碍是我不知道输入有效负载是什么样的。但我需要将任何数字字符串转换为数字,并将 "true" / "false" 转换为 true / false.
我是否需要递归遍历整个对象/对象数组并检查和分配每个字段,或者是否有某种快捷方式?
当然,如果我知道输入负载的结构,这就不是什么大问题了。不幸的是,这些是我的要求。
@machaval 是正确的,你必须遍历。
有一种方法,根据您的背景,它可能很简单。这应该是一个好的开始,即使它有点不灵活:
%dw 2.0
output application/dw
var ds = [
{
a: "1",
b: "2",
c: "str",
d: ["1","2","str","false"],
e: "true"
},
{
a: "1",
b: "2",
c: "str",
d: ["1","2","str","false"],
e: "true"
}
]
import try,orElseTry,orElse from dw::Runtime
// Overloaded functions that traverse the types that I know
// my data structure contains. I only traverse arrays and objects
// and the combination thereof. If you expect more types in your
// data you will have to add one overloaded function per datatype
// you expect to have up and beyond what I show below.
fun traverse(a: Array) = a map traverse($)
fun traverse(o: Object) = o mapObject {($$): traverse($)}
fun traverse(s: String) =
try(() -> s as Number)
orElseTry(() -> s as Boolean)
orElse(s)
---
traverse(ds)
编辑:包括布尔值
我最大的障碍是我不知道输入有效负载是什么样的。但我需要将任何数字字符串转换为数字,并将 "true" / "false" 转换为 true / false.
我是否需要递归遍历整个对象/对象数组并检查和分配每个字段,或者是否有某种快捷方式?
当然,如果我知道输入负载的结构,这就不是什么大问题了。不幸的是,这些是我的要求。
@machaval 是正确的,你必须遍历。
有一种方法,根据您的背景,它可能很简单。这应该是一个好的开始,即使它有点不灵活:
%dw 2.0
output application/dw
var ds = [
{
a: "1",
b: "2",
c: "str",
d: ["1","2","str","false"],
e: "true"
},
{
a: "1",
b: "2",
c: "str",
d: ["1","2","str","false"],
e: "true"
}
]
import try,orElseTry,orElse from dw::Runtime
// Overloaded functions that traverse the types that I know
// my data structure contains. I only traverse arrays and objects
// and the combination thereof. If you expect more types in your
// data you will have to add one overloaded function per datatype
// you expect to have up and beyond what I show below.
fun traverse(a: Array) = a map traverse($)
fun traverse(o: Object) = o mapObject {($$): traverse($)}
fun traverse(s: String) =
try(() -> s as Number)
orElseTry(() -> s as Boolean)
orElse(s)
---
traverse(ds)
编辑:包括布尔值