JSONata: How to transform result based on if a property is present in input

60 views Asked by At

I am trying to transform the JSON object using JSONata. I want the result object to have a property, "property_3" if input contains "prop3". If the input doesn't contain "prop3" then the result shouldn't have "property_3" as well. Can I achieve this through JSONata and what should be the JSONata expression for this?

Input 1

{
  "prop1":"prop1 value1",
  "prop2":"prop2 value1",
  "prop3":"prop3 value1"
}

Expected output 1

{
  "property_1": "prop1 value1",
  "property_2": "prop2 value1",
  "property_3": "prop3 value1"
}

Input 2

{
  "prop1":"prop1 value1",
  "prop2":"prop2 value1"
}

Expected output 2

{
  "property_1": "prop1 value1",
  "property_2": "prop2 value1"
}
1

There are 1 answers

0
mralex On

One way to solve is to iterate over the keys of your input object and replace the prop substring:

$keys($){
  $replace($, "prop", "property_"): $lookup($$, $)
}

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