Search code examples
jsonata

Applying function to each key in a object inside array


I have the following json:

{
  "result": [
      {
          "codigo_produto": "10162",
          "gtin": "0000040084107",
          "descricao_produto": "Kinder Ovo",
          "un_venda": "UN",
          "segmento_1": "10000",
          "cod_segmento_1": "Geral"
      },
      {
          "codigo_produto": "185680",
          "gtin": "7892840127114",
          "descricao_produto": "Pingo D'ouro Picanha 65gr",
          "un_venda": "UN",
          "segmento_1": "10000",
          "cod_segmento_1": "Geral"
      }
  ]
}

And I would like to apply the function $replace($value, /[^a-zA-Z0-9 ]/, '') to every key in the objects that are inside the array to make sure that no special characters exist in every value of the object.

I have tried the following:

$ ~> | result |  
    $each(
        function($object) {
            $each($object, function($k, $v) {
                {$k: $replace($v, /[^a-zA-Z0-9 ]/, '') }
            })
        } 
    ) ~> $merge() |

But it gives the error Argument 1 of function "each" does not match function signature

What should I do?


Solution

  • You can do it with a map operation and then $each + $merge pair:

    result.(
      $each($, function($v, $k) {
        { $k: $replace($v, /[^a-zA-Z0-9 ]/, '') }
      }) ~> $merge()
    )
    

    Check it out on the playground: https://stedi.link/ouranAW