Search code examples
jsonjsonpathjsonata

Is it possible to combine columns and rows which are seperate in JSON, using JSONata or JSONPath?


I want to use JSONata (https://try.jsonata.org/) or JSONPath to combine column data from a Columns array with row data from a Rows array in the same JSON. I think I need to have a for each row with another for each column nested inside. Can I do this using JSONata or JSONPath?

**INPUT**
{
  "Columns": [
    {
      "ColumnName": "Name",
      "ColumnType": "string"
    },
    {
      "ColumnName": "Id",
      "ColumnType": "int"
    }
  ],
  "Rows": [
    ["Alice", 1],
    ["Bob", 2],
    ["Carl", 3]
  ]
}

**OUTPUT**
{
  "combinedData": [
    {
      "Name": "Alice",
      "Id": 1
    },
    {
      "Name": "Bob",
      "Id": 2
    },
    {
      "Name": "Carl",
      "Id": 3
    }
  ]
}

Solution

  • Create smaller objects, one for each key, then merge at the end. See Playground demo

    {
      "combinedData": $.Rows ~> $map(function($row) { 
        $.Columns[].ColumnName ~> $map(function($name, $index){
          {$name: $row[$index]}
        }) ~> $merge
      })
    }