Mule 4: Dataweave filter or search through json object of objects?

I have data from a 3rd party query being returned to me in the following format:

{
    "attendeeid": "1234",
    "responses": {
        "23": {
            "questionid": "555",
            "fieldname": "verifyemail",
            "name": "Verify Email Address",
            "pageid": "0",
            "page": null,
            "auto_capitalize": "0",
            "choicekey": "[email protected]",
            "response": "[email protected]"
        },
        "24": {
            "questionid": "777",
            "fieldname": "verifycity",
            "name": "Verify City",
            "pageid": "0",
            "page": null,
            "auto_capitalize": "0",
            "choicekey": "San Jose",
            "response": "San Jose"
        },
        "25": {
            "questionid": "888",
            "fieldname": "verifyphone",
            "name": "Verify Phone",
            "pageid": "0",
            "page": null,
            "auto_capitalize": "0",
            "choicekey": "1234567890",
            "response": "1234567890"
        }
    }
}

Normally, I would expect responses to be an array of responses and would use map/filter to search for responses containing certain values.

In this case, responses doesn't seem to be an array, so I am not sure how to treat this.

Is there an easy way to turn responses into an array so that I can use a traditional map method?

My end goal is that I want to be able to search through responses for any results that have fieldname == verifyemail, giving me the final output of:

[{
    "questionid": "555",
    "fieldname": "verifyemail",
    "name": "Verify Email Address",
    "pageid": "0",
    "page": null,
    "auto_capitalize": "0",
    "choicekey": "[email protected]",
}]

Where should I start with getting the data into the format I need for my filter?


Solution 1:

You could probably use valuesOf (https://docs.mulesoft.com/dataweave/2.3/dw-core-functions-valuesof) to get going. That should help you get in th right direction.

%dw 2.0
output application/json
---
valuesOf(payload.responses) filter ($.fieldname ~= "verifyemail")

Solution 2:

The input is not an array but an object, meaning that it is a collection of key-values. That's the reason you can not use filter() nor map() directly on it. You can use filterObject() to perform a filter over the object key-pairs. Then use pluck() to pickup the resulting values into an array.

%dw 2.0
output application/json
---
payload.responses 
    filterObject ((value, key, index) -> value.fieldname == "verifyemail") 
    pluck $