使用 DataWeave 检查 JSON 中的空字段值和/或缺失字段值
Checking empty and or missing field value in JSON with DataWeave
您好,我正在使用 Mulesoft 3.8.4 中的 Dataweave 将 JSON 转换为 JSON。我正在使用 JSON(较大文件的一部分)
中的以下几行
..
"someField": "12",
"otherField": "5441",
..
我想将 'someField' 格式化为总长度为 4 (0012) 的零左填充字符串。我还想将该值连接到也需要填充但总长度为 6 的 otherField。
为了防止填充和连接失败,我必须检查该字段是否存在,而不是空的,并且它必须是数字。
我有以下代码:
"My Number": someField as :number as :string {format: "0000"} ++ otherField as :number as :string {format: "0000"}
when somefield != null
and someField != ""
and someField is :number
and otherField != null
and otherField != ""
and otherField is :number
otherwise "",
但这失败了,因为 'is :number' returns false 因为实际上该值是一个字符串。当值为空时,检查 'and someField as :number is :number' 之类的内容也会失败。最好的检查方法是什么?
感谢您的帮助。
约翰
好吧,我自己想出来了。最麻烦的部分是查看该值是否为数字。由于 JSON 中的节点可能不存在、为空或文本,因此很难在一个 when-otherwise 中进行这些测试。
还有一个要求是总是应该有一个返回值。所以当 null 不是一个选项时跳过。
将数字测试更改为正则表达式有帮助。为了使代码更具可读性,我还添加了一些我也可以重复使用的函数。
代码现在看起来像这样:
%function repeat(char, times) (char ++ repeat(char, times - 1)) when times > 0 otherwise ""
%function pad(field, count) field as :number as :string {format: repeat('0', count)}
%function toNumber(value, count) (pad(value, count)
when value matches /^\d+$/
otherwise "")
...
"My Number" : "" when someField == null
otherwise "" when otherField == null
otherwise toNumber(someField, 4) ++
toNumber(filterUpper(otherField), 6),
...
repeat 函数给出了一个包含第 n 个重复字符的字符串。 pad 函数左侧用零填充我转换为字符串的数字。在此函数中,我使用 repeat 函数提供带有变量零字符串的格式。
toNumber 是一个检查,看看我们是否只使用数字。
希望其他人也能从中受益。
您好,我正在使用 Mulesoft 3.8.4 中的 Dataweave 将 JSON 转换为 JSON。我正在使用 JSON(较大文件的一部分)
中的以下几行..
"someField": "12",
"otherField": "5441",
..
我想将 'someField' 格式化为总长度为 4 (0012) 的零左填充字符串。我还想将该值连接到也需要填充但总长度为 6 的 otherField。 为了防止填充和连接失败,我必须检查该字段是否存在,而不是空的,并且它必须是数字。
我有以下代码:
"My Number": someField as :number as :string {format: "0000"} ++ otherField as :number as :string {format: "0000"}
when somefield != null
and someField != ""
and someField is :number
and otherField != null
and otherField != ""
and otherField is :number
otherwise "",
但这失败了,因为 'is :number' returns false 因为实际上该值是一个字符串。当值为空时,检查 'and someField as :number is :number' 之类的内容也会失败。最好的检查方法是什么?
感谢您的帮助。
约翰
好吧,我自己想出来了。最麻烦的部分是查看该值是否为数字。由于 JSON 中的节点可能不存在、为空或文本,因此很难在一个 when-otherwise 中进行这些测试。 还有一个要求是总是应该有一个返回值。所以当 null 不是一个选项时跳过。
将数字测试更改为正则表达式有帮助。为了使代码更具可读性,我还添加了一些我也可以重复使用的函数。
代码现在看起来像这样:
%function repeat(char, times) (char ++ repeat(char, times - 1)) when times > 0 otherwise ""
%function pad(field, count) field as :number as :string {format: repeat('0', count)}
%function toNumber(value, count) (pad(value, count)
when value matches /^\d+$/
otherwise "")
...
"My Number" : "" when someField == null
otherwise "" when otherField == null
otherwise toNumber(someField, 4) ++
toNumber(filterUpper(otherField), 6),
...
repeat 函数给出了一个包含第 n 个重复字符的字符串。 pad 函数左侧用零填充我转换为字符串的数字。在此函数中,我使用 repeat 函数提供带有变量零字符串的格式。 toNumber 是一个检查,看看我们是否只使用数字。
希望其他人也能从中受益。