Search code examples
jsonata

How to Replace Substring in all Elements of Object without Destroying it


I need to replace substrings of all elements in an object.

E.g. replace all 'X' in val1 and val2:

{
    "input": [
        {
            "val1": "008 X 148",
            "val2": "SOME X DATA"
        },
        {
            "val1": "X 005 5PM",
            "val2": "SOME X DATA"
        },
        {
            "val1": "MODTOX",
            "val2": "X SOME X DATA"
        }
    ]
}

My first intention was to use $map and then $each, like this:

$map(input, function($i) 
    { $each($i, function($s) 
        { $replace($s, "X", "Y" ) 
        })
    })

, but as expected, this destroys the object.

Any suggestion? Finally 'input' should still be of same structure.


Solution

  • You need to use the transform operator to modify a copy of the input data:

    $ ~> | input |  $each(function($v, $n){{$n: $replace($v, "X", "Y") }} ) ~> $merge() |
    

    See https://try.jsonata.org/yeKAKg_U_