To_dictionary can be used to convert an array into multiple objects where each object takes the value of a defined key.
Syntax
json_object to_dictionary(array $input, expr &key, expr &value)
Groups all objects within the $input
array by a defined common &key
. It converts the input array into a single object which in turn contains an object for each unique &key
and applies an expression defined by &value
to each of these objects.
Parameters
$input: The array to evaluate.
$key: The items within each array to group by.
$value: The expression to apply to object.
Example
{
"SalesData": [
{
"Region": "Germany",
"Product": "Apple",
"Units": "51"
},
{
"Region": "Denmark",
"Product": "Apple",
"Units": "99"
},
{
"Region": "Germany",
"Product": "Orange",
"Units": "66"
},
{
"Product": "Apple",
"Units": "51"
}
]
}
{
SalesDataByRegion: to_dictionary(SalesData, &Region, &@.Product)
}
{
"SalesDataByRegion": {
"Germany": [
"Apple",
"Orange"
],
"Denmark": [
"Apple"
],
"_": [
"Apple"
]
}
}
This example shows to_dictionary
being used to create a list of each product sold in a region where both the product name and region names exist as key/value pairs within each object. Two of these objects have a region with value Germany, one has a region with value Denmark and one has no region value. The $value
expression then uses the current node scope operator to extract ONLY the Product
from each object. The result is a list of each product per region.
Notes
Where the defined key does not exist, objects will be grouped together under a default key, “_”.