skip to Main Content

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
    }
  ]
}

2

Answers


  1. 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
      })
    }
    
    Login or Signup to reply.
  2. It could be done using some of the built-in operators and functions of JSONata:

    {
      "combinedData": Rows.(
        $#$i.{
          $$.Columns[$i].ColumnName: $
        } ~> $merge
      )
    }
    

    Check it out live on the Stedi Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search