Search code examples
dynamics-crmpowerappspower-automate

How to retrieve the data value and convert array to dictionary using power automate expression?


I have a form that sends data to a power automate flow. The output of the trigger for the flow is shown below.

enter image description here

How do I transform the data to output this format

{
    "Form ID": "67249",
    "Timezone": "America/Denver",
    "User Timezone": "America/Denver"
 }

So I can use property names to store the output in variables?

I tried using array index and it worked but when a field is omitted the index moves up and a wrong variable value is stored. Also tried using select and parse json but the action outputs a key which is one every object in the array. Select returned a result but not able to stored it in different varables.


Solution

  • It's a bit clunky but you can do it like this ...

    Flow

    Explanation

    First, I initialise an Array variable with a set of key value pairs. It's not your data specifically but that doesn't matter. It looks like this ...

    [
      {
        "key": "Key 1",
        "value": "Value 1"
      },
      {
        "key": "Key 2",
        "value": "Value 2"
      },
      {
        "key": "Key 3",
        "value": "Value 3"
      },
      {
        "key": "Key 4",
        "value": "Value 4"
      },
      {
        "key": "Key 5",
        "value": "Value 5"
      }
    ]
    

    Second & third, I initialise two empty variables of type Object. There's a reason why I need a temp version which I'll explain a little later on.

    Fourth, you need to loop through the array of key value pairs. It's within that array that you're going to perform the magic.

    Fifth, you need to use a Set variable operation and make sure it's assigned to the temp resulting object.

    The expression within that step is ...

    addProperty(variables('Resulting Object'), item()['key'], item()['value'])
    

    ... and the reason for needing the temp variable is because when using the Set variable operation, you can't self assign. So basically, an expression cannot be used against the variable that you're setting. You can see in the addProperty expression, we're referring to the non-temp resulting object variable, not the temp one.

    Sixth, now transfer the temp object over to the main one. We do this because the next time the loop comes around, it will refer to the main/non-temp object and retain all of the existing properties that we previously added.

    Finally, this is the end result ...

    {
      "Key 1": "Value 1",
      "Key 2": "Value 2",
      "Key 3": "Value 3",
      "Key 4": "Value 4",
      "Key 5": "Value 5"
    }
    

    Note: I set the concurrency on the loop to be 1 so as to preserve the order of the key value pairs. You can choose to do this or not.