Search code examples
jsonjsonata

Need help in restructuring data with JSONata


I cant get it done, need some community brainpower here. Please find the source data and the desired results below. I am currently familiarizing myself with JSONata.

I have tried almost all combinations in the JSONata docs, but I am getting strange results back.

Source data

[
  {
    "id": 784521,
    "name": "T-Shirt - Red / 60 XXL",
    "properties": [
      {
        "name": "customization",
        "value": "Text, Logo"
      },
      {
        "name": "customization_text",
        "value": "John Doe"
      },
      {
        "name": "customization_text_pos",
        "value": "Left"
      },
      {
        "name": "customization_logo",
        "value": "https://https://picsum.photos/200/300"
      },
      {
        "name": "customization_logo_pos",
        "value": "Right"
      }
    ],
    "quantity": 8,
    "sku": "888-111"
  },{
    "id": 154857,
    "name": "Pullover - Blue / 48 L",
    "properties": [
      {
        "name": "customization",
        "value": "Text"
      },
      {
        "name": "customization_text",
        "value": "John Doe"
      },
      {
        "name": "customization_text_pos",
        "value": "Right"
      }
    ],
    "quantity": 4,
    "sku": "555-111"
  }
]

Desired result

{
  "products": [
    {
      "name": "T-Shirt - Red / 60 XXL",
      "quantity": 8,
      "customization": "Text, Logo",
      "customization_text": "John Doe",
      "customization_text_pos": "Left",
      "customization_logo": "https://https://picsum.photos/200/300",
      "customization_logo_pos": "Right"
    },
    {
      "name": "Pullover - Blue / 48 L",
      "quantity": 4,
      "customization": "Text",
      "customization_text": "John Doe",
      "customization_text_pos": "Right",
      "customization_logo": "",
      "customization_logo_pos": ""
    }
  ]
}

Solution

  • I'm not sure how important for your case to populate the missing properties with an empty string value, but if not - reducing your properties array into an object lets you achieve the result:

    {
      "products": $$.(
        $item := $;
        
        properties{
          "name": $item.name,
          "quantity": $item.quantity,
          name: value 
        }
      )
    }
    

    See it live: https://stedi.link/6htarTz