使用DataWeave在JSON中检查空和缺少的字段值

问题描述:

您好我正在使用Mulesoft 3.8.4中的Dataweave将JSON转换为JSON。我正在与在JSON以下行(较大文件的一部分)使用DataWeave在JSON中检查空和缺少的字段值

.. 
"someField": "12", 
"otherField": "5441", 
.. 

我想格式化工作“someField”到零左填充字符串的4(0012)的总长度。我也想把这个值连接到另一个也需要填充的字段,但总长度为6. 为了防止填充和连接失败,我必须检查字段是否存在,而不是空的,它必须是数字。

我有以下代码:

"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 "", 

但这种失败,因为“是:数”,因为实际值是一个字符串,返回false。当值为空时,检查'and someField as:number is:number'等内容也会失败。什么是最好的检查方法?

Thanx帮助。

约翰

好吧我想出了自己。最主要的一点是看看价值是否是一个数字。由于JSON中的节点可能不是现有的,空的或文本的,因此很难在其中一次进行这些测试,否则。 还有一个要求是总是应该有一个返回值。因此,当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), 
... 

重复功能给出了n次重复字符的字符串。填充功能会将我的编号转换为零的字符串。在这个函数中,我使用重复函数来为变量零的字符串提供格式。 toNumber是一个检查,看看我们是否只使用数字。

希望别人也能从中受益。