Search code examples
jsonata

Turn a JSON array of key/value pairs into object properties


I'm trying to use JSONata to convert arrays of "key/value" objects into properties of the parent object. My input looks like this:

[
  {
    "city": "Ottawa",
    "properties": [
      {
        "name": "population",
        "value": 37
      },
      {
        "name": "postalCode",
        "value": 10001
      },
      {
        "name": "founded",
        "value": 1826
      }
    ]
  },
  {
    "city": "Toronto",
    "properties": [
      {
        "name": "population",
        "value": 54
      },
      {
        "name": "postalCode",
        "value": 10002
      }
    ]
  }
]

I'm struggling to generate the output I need, I've seen examples that reference explicit elements, like in this answer, but I need the properties to be converted "dynamically" since I don't know them in advance. I think I need something like this, but I'm missing some particular function:

$[].{
    "city": city,
    properties.name: properties.value
}

This is the output I need to generate:

[
  {
    "city": "Ottawa",
    "population": 37,
    "postalCode": 10001,
    "founded": 1826
  },
  {
    "city": "Toronto",
    "population": 54,
    "postalCode": 10002
  }
]

The properties arrays don't always contain the same keys, but the city attributes are always present.


Solution

  • You can use the reduce operator, as described in the Grouping docs here:

    $[].(
      $city := city;
      properties{ "city": $city, name: value }   
    )
    

    You can play with it live: https://stedi.link/uUANwtE