access value of an array through the name in the Expression in Power Automate/ MS flow
-
16-02-2021 - |
Question
I have created an empty list and appending to it in the flow, at the end, I need to get the value of a specific key through an Expression, Is this possible? and if yes, how?
Please see the below screenshots.
Initialise:
Append:
I am appending data to this array in a Do while loop, the content of each run (total 2 run) is shown below:
First Run:
Second Run:
And the output of Compose"
[
{
"name": "Fy2020",
"value": 2.5
},
{
"name": "Fy2021",
"value": 2.5
}
]
Retrieve and assign it to another variable:
I have tried different approaches and got different errors:
variables('FYearsValues')?['value']?[0] erorr:
'The template language expression 'variables('FYearsValues')?['value']?[0]' cannot be evaluated
because property 'value' cannot be selected. Array elements can only be selected using an
integer index. Please see https://aka.ms/logicexpressions for usage details.'.
variables('FYearsValues')?['Value']?[0] Error:
The template language expression 'variables('FYearsValues')?['Value']?[0]' cannot be
evaluated because property 'Value' cannot be selected. Array elements can only be selected using an
integer index. Please see https://aka.ms/logicexpressions for usage details.'.
variables('FYearsValues')[0] Error:
The variable 'FYCounter_' of type 'Integer' cannot be initialized or updated with value '{
"name": "Fy2020",
"value": 2.5
}' of type 'Object'. The variable 'FYCounter_' only supports values of types 'Integer'.
and for this: variables('FYearsValues')['Fy2020'] Error:
Unable to process template language expressions in action 'Set_variable_3' inputs at line '1' and
column '2857': 'The template language expression 'variables('FYearsValues')['Fy2020']' cannot be
evaluated because property 'Fy2020' cannot be selected. Array elements can only be selected using an
integer index. Please see https://aka.ms/logicexpressions for usage details.'.
The best formula for me would be something like this
variables('FYearsValues')['Fy2020'] which needs to return 2.5 (i.e.value)
but I can work with indexes too (e.g. variables('FYearsValues')[0] which needs to return 2.5 (i.e.value)
Solution
If it's an array, you would access it with index starting at 0 like
variables('MyArray')?[1]
Index can be a variable as well, in that case it would be like
variables('MyArray')?[variables('varIndex')]
However, if it's a JSON object collection, then first need to find the item by the index and then find the items' value by property name. In the example below, [results] is a collection of items, but retrieving user email by property
body('Parse_JSON')?['d']?['results'][1]['User']['Email']