2017-08-02 40 views
0

您好我正在使用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幫助。

約翰

回答

0

好吧我想出了自己。最主要的一點是看看價值是否是一個數字。由於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是一個檢查,看看我們是否只使用數字。

希望別人也能從中受益。