简体   繁体   中英

DataWeave convert XML to JSON

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
}
]
}

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.

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.*item.@.name // 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

    }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM