Loading

How To Convert Single XML Element To JSON Array In Dataweave

Data pubblicazione: Jul 25, 2025
Fasi

QUESTION

When converting XML payloads to JSON and using "duplicateKeyAsArray=true" to convert duplicate key names to an array it works great.  However, if there is only 1 element, the value will be returned as an object instead of an array with a single object. Is there a way to keep the field consistently returning an array?

My XML payload:

<?xml version='1.0' encoding='UTF-8'?>
<ns0:Project xmlns:ns0="http://xmlns.example.com/Product/">
    <ns0:Products>
        <ns0:RatingInfo>
            <ns0:Rating>
                <ns0:RatingMethod>TEST</ns0:RatingMethod>
                <ns0:RatingDescriptors>
                    <ns0:RatingDescriptor>DESC1</ns0:RatingDescriptor>
                    <ns0:RatingDescriptor>DESC2</ns0:RatingDescriptor>
                </ns0:RatingDescriptors>
            </ns0:Rating>
        </ns0:RatingInfo>
    </ns0:Products>
</ns0:Project>
 

ANSWER

Yes, we can use the Dataweave update operator to update the single element into an array.

For example:

%dw 2.0
output application/json skipNullOn="everywhere"
var p0 = payload

var p1 = p0 update {
case descs at .*Project.*Products.*RatingInfo.*Rating.*RatingDescriptors -> {
   RatingDescriptor: descs.*RatingDescriptor
 }
}

var p2 = p1 update {
case rate at .*Project.*Products.*RatingInfo -> {
   Rating: rate.*Rating
 }
}

---
p2
 

ADDITIONAL INFORMATION

https://blogs.mulesoft.com/news/anypoint-platform/update-fields-with-dataweave/
Numero articolo Knowledge

001116066

 
Caricamento
Salesforce Help | Article