Matthew Colley
Matthew Colley

Reputation: 11446

Mule Dataweave Cannot coerce a :null to a :number

I am building a Java map of two different Json data streams. However if one of the streams contains a null value in the quantity, the flow will error with the following condition:

 ($.itemid) : '"' ++ skuLookup[$.sku][0].qty as :number as :string {format: "#.0000"} ++ '"'
                                                                         ^
 Cannot coerce a :null to a :number 
 (com.mulesoft.weave.mule.exception.WeaveExecutionException). Message payload is of type: String

The ideal scenario would be ignore the null values within the iteration Here is the dataweave as untouched:

  %output application/java
  %var skuLookup =  flowVars.SSRCreateStarshipItems groupBy $.sku
  ---
  flowVars.SSRGetOrderItems map ({
  ($.itemid) : '"' ++ skuLookup[$.sku][0].qty as :number as :string 
  {format: "#.0000"} ++ '"'
  })

Here is my ideal solution, however I cant seem to get it to work:

  %output application/java
  %var skuLookup =  flowVars.SSRCreateStarshipItems groupBy $.sku
  ---
  flowVars.SSRGetOrderItems map ({
  ($.itemid) : '"' ++ skuLookup[$.sku][0].qty as :number as :string 
  {format: "#.0000"} ++ '"'
  }) when skuLookup[$.sku][0].qty != null

Upvotes: 0

Views: 7235

Answers (1)

granthbr
granthbr

Reputation: 311

Setting the default value resolve your problem. For example, If you were passing in a payload such as this:

{
    "testMap": [
        {
            "testName": "TestName",
            "Value": "3"
        },
        {
            "testName": "TestName",
            "Value": null
        }
    ]
}

You could convert the Value key to a number or pass null with this:

%dw 1.0
%input payload application/json
%output application/json
---
payload.testMap map (data, index) -> {

  testName: data.testName,
  Value: data.Value as :number as :string {format: "#.0000"} default null
}

And this is the result:

[
  {
    "testName": "TestName",
    "Value": "3.0000"
  },
  {
    "testName": "TestName",
    "Value": null
  }
]

Also, if you want to remove the key completely, insert this after the output header for json:

skipNullOn="everywhere"

Upvotes: 1

Related Questions