Search code examples
jsonata

How to transform JSON array?


I need to transform this json array:

[
    {
        "timestamp": "2025-01-19T17:00:00Z",
        "absoluteDeviationsX": [10, 11, 12 ]
    },
    {
        "timestamp": "2025-01-20T17:00:00Z",
        "absoluteDeviationsX": [20, 21, 22 ]
        ]
    }
]

to:

[
    {
    "timestamp": "2025-01-19T17:00:00Z",
    "absoluteDeviationsX0": 10,
    "absoluteDeviationsX1": 11,
    "absoluteDeviationsX2": 12,
    },
    {
    "timestamp": "2025-01-20T17:00:00Z",
    "absoluteDeviationsX0": 20,
    "absoluteDeviationsX1": 21,
    "absoluteDeviationsX2": 22,
    }
]

with JSONata.

I need this to process data in Infinity plugin in Grafana.


Solution

  • $map($, function($v) {
      $merge([
        { 'timestamp': $v.timestamp },
        $map($v.absoluteDeviationsX, function ($v, $i) {
          { 'absoluteDeviationsX' & $i: $v }
        })
      ])
    })
    

    Playground link: https://jsonatastudio.com/playground/71584a20

    Explanation: the first $map function iterates over all items of the root input and produces a duplicate array. The second $map iterates over the deviations array, transforms each item into an object and appends the item index to each key name. Eventually, all of transformed objects are merged with $merge and passed back to the first $map function as a final output.