Search code examples
jsonjsonata

Convert JSON input to output


How can I convert the following JSON with JSONata. I need to convert the "value" object, to be an array of key/pair values

Input:

{
    "data": [
        {
            "attribute": "line_items",
            "value": [
                {
                    "item_base_total_amount_base": "89.00",
                    "item_order_number": ""
                }
            ]
        },
        {
            "attribute": "tax_breakdown",
            "value": [
                {
                    "tax_rate": "0",
                    "tax_base": "635.00"
                }
            ]
        }
    ]
}

Output:

{
    "data": [
        {
            "attribute": "line_items",
            "value": [
                {
                    "attribute": "item_base_total_amount_base",
                    "value": "89.00"
                },
                {
                    "attribute": "item_order_number",
                    "value": ""
                }
            ]
        },
        {
            "attribute": "tax_breakdown",
            "value": [
                {
                    "attribute": "tax_rate",
                    "value": "0"
                },
                {
                    "attribute": "tax_base",
                    "value": "635.00"
                }
            ]
        }
    ]
}

Thanks

Tried with each function recursively but did not manage to make it work


Solution

  • You can use the transform operator to update only the nested "value" attribute with the help of the $each function:

    $ ~> |data|{
      "value": $each(value[0], function($value, $attribute){{
        "attribute": $attribute,
        "value": $value
      }})
    }|
    

    Check it out on the Stedi Playground: https://stedi.link/TJV4zaY