user94538
user94538

Reputation: 177

List of map to json using Dataweave

How can i convert list of map to json using dataweave for the below example.

Input is list of map. For example, it has 3 elements id, value1, value2

[
    {
        "id" : "123",
        "value1" : "678"
        "value2" : "900"
    },
    {
        "id" : "456",
        "value1" : "679",
        "value2" : "901"
    }
]

Expected output:

Root element is data, value of id (123) is the key and value2, value 3 are elements in the object.

{
    "data" : {
        "123" : {
            "value1" : "678",
            "value2" : "900"
        },
        "456" : {
            "value1" : "679",
            "value2" : "901"
        }
    }
}

I tried to implement dataweave script but its not giving the exact output i was looking for. How can i write dataweave script to achieve this?

Upvotes: 0

Views: 407

Answers (2)

Abhay
Abhay

Reputation: 324

Try the below script

data: { (payload map { ($.id as :string): $ -- $.id }) }

Here, id is used as key and from value we remove the corresponding id

Upvotes: 0

Jesse0451
Jesse0451

Reputation: 81

data: ( payload.*id map '$':payload[$$]  - "id") reduce ($$ ++ $)

Should do the trick.

Upvotes: 1

Related Questions