Turn array of objects into list of objects in Jsonata

Viewed 90

I need to write a Jsonata query to turn array of objects into list of key/value objects where the key is the index of the object. For example I need to turn the following JSON structure

{
  "Account": {
    "Account Name": "Firefly",
    "Order": [
      {
        "OrderID": "order103",
        "Product": [
          {
            "Product Name": "Bowler Hat",
            "ProductID": 858383,
            "SKU": "0406654608",
            "Description": {
              "Colour": "Purple",
              "Width": 300,
              "Height": 200,
              "Depth": 210,
              "Weight": 0.75
            },
            "Price": 34.45,
            "Quantity": 2
          },
          {
            "Product Name": "Trilby hat",
            "ProductID": 858236,
            "SKU": "0406634348",
            "Description": {
              "Colour": "Orange",
              "Width": 300,
              "Height": 200,
              "Depth": 210,
              "Weight": 0.6
            },
            "Price": 21.67,
            "Quantity": 1
          }
        ]
      }
    ]
  }
}

Into the following json structure.

{
  "result": {
    "0": {
      "Product Name": "Bowler Hat",
      "ProductID": 858383,
      "SKU": "0406654608",
      "Description": {
        "Colour": "Purple",
        "Width": 300,
        "Height": 200,
        "Depth": 210,
        "Weight": 0.75
      },
      "Price": 34.45,
      "Quantity": 2
    },
   "1": {
      "Product Name": "Trilby hat",
      "ProductID": 858236,
      "SKU": "0406634348",
      "Description": {
        "Colour": "Orange",
        "Width": 300,
        "Height": 200,
        "Depth": 210,
        "Weight": 0.6
      },
      "Price": 21.67,
      "Quantity": 1
    }
  }
}

I appreciate any help to find the right Jsonata query or queries that could achieve this transformation.

1 Answers

One solution that I found is to use positional variable binding (#).

{
  "result": Account.Order.Product#$i{
    $string($i): $
  }
}

The full solution on JSONata Playground: https://stedi.link/4Pj8Rvd

Related