Search code examples
jsoncsvmuleanypoint-studiodataweave

Ignore empty string when mapping CSV to JSON using Dataweave


I am mapping from CSV to JSON and some of the CSV fields are showing as "" in the JSON mapping. How can I get Dataweave to ignore "" and only populate when there is a value?

I have tried skipNullOn but this doesn't work. Is there another way to do it or do I have to add an when condition around each field?

Seeing this error with the recursive solution:

enter image description here

Thanks


Solution

  • Try this solution, adapted from this answer. We recursively decide if we want to remove a field from the model, using match in the acceptable function to remove empty strings, nulls, and empty objects.

    %dw 1.0
    %output application/json
    
    %function acceptable(value) (
        value match {
            :null -> false,
            o is :object -> o != {},
            s is :string -> s != "",
            default -> true
        }
    )
    
    %function filterKeyValue(key, value) (
        {(key): value} when acceptable(value) otherwise {}
    )
    
    %function removeFields(x)
        x match {
            a is :array -> a map removeFields($),
            o is :object -> o mapObject
                (filterKeyValue($$, removeFields($))),
            default -> $
        }
    ---
    removeFields(payload)