Search code examples
jsonmuledataweavemulesoft

Mule- Mapping key and values to new keys and values


I need to extract key and values from json to form different json output

Input Json

{"somekey":"xyz",
"properties":{
"key1":"value1",
"key2":"value2"
.....
}

Expected Output Json

{"somekey":"xyz",
"properties":{
"mainkey1": "value1"
"mainkey2": "value2"
....
}
}

I need to add "main" to the existing key and read all the keys. Consider there's n number of key value pairs in properties. How can this be done dwl script?

I tried to map the objects using payload map and write manually the entire keys. As new key value pairs get added i had to write each keys manually into mapping.


Solution

  • You can use update operator to update the parent object. Update will keep the existing keys and only update the props object. To concatenate the property keys a mapObject can be used.

    %dw 2.0
    output application/json
    ---
    payload update {
        case props at .properties -> props mapObject ((value, key) -> {
            ("main" ++ (key as String)): value
        })
    }