Home > OS >  DataWeave convert XML to JSON
DataWeave convert XML to JSON

Time:09-20

I have below xml i have requirement like need to convert this to json and map metadata key names with row values using dataweave the outcome is also attached in the same

<dataset>
<metadata>
<item name="id" type="xs:int"/>
<item name="name" type="xs:string"/>
<item name="description" type="xs:string"/>
<item name="time" type="xs:string"/>
</metadata>
<data>
<row>
<value>7</value>
<value>varsha</value>
<value>ads</value>
<value>10</value>
</row>
<row>
<value>8</value>
<value>dhal</value>
<value>dd</value>
<value>09</value>
</row>
</data>
</dataset>

output:

available:{
[
{
"id" : 7,
"name" : varsha,
"description" : ads,
"time" : 10
},
{
"id" : 8,
"name" : dhal,
"description" : dd,
"time" : 09
}
]
}

CodePudding user response:

Your output json is invalid, use any json validator(https://www.jsonlint.com/) to get that corrected.

Coming to your solution to assign keys dynamically from metadata element, try like below:

%dw 2.0
output application/json  writeAttributes=true
---

  available: payload..*row map ($ mapObject ((value, key, index) -> do {
      var keys = payload.dataset.metadata.*[email protected] // store metadata name atrributes in an array(keys)
      ---
         // iterate over all row elements for value and dynamically assign them keys from keys array
        ((keys)[index] as String): value

    }))

CodePudding user response:

You can keep the fieldNames in a separate variable after fetching them from metadata and then map those fields based to index to each of the row data.

%dw 2.0
output application/json
var fieldNames = payload.dataset.metadata.*item.@name
---
available: payload.dataset.data.*row map ((rowData) -> {
    (fieldNames map ((fieldName, feildIndex) -> {
        (fieldName): rowData.*value[feildIndex]
    }))
})

Notice how I have wrapped the fieldNames map ... mapper around an object destructor {()}. Its because originally it will return an array of each field as an item. However by wrapping them around a parenthesis each item will be "destructed" and then will be collected as key value pair as a single object.

  • Related