How to dynamically set a value based on another key-value

In my JSON object I have one key-value, condition, from which I want to decide which other object to set in a third value. This condition can vary in different datasets/objects. How can that be done using JmesPath or some copy-move-transformer? So far I have only seen examples with hardcoded control values.

example:

{
    "condition":"good",
    "states":{
        "bad":{
            "emotion":"sad",
            "color":"red"
        },
        "good":{
            "emotion":"happy",
            "color":"green"
        },
        "neutral":{
            "emotion":"meh",
            "color":"yellow"
        }
    }
}

resultState = states that have the key of condition

{
  "resultState": {
    "emotion":"happy",
    "color":"green"
  }
}

I found a solution based on this former post. By rewriting the example object to an array containing the key-value for comparison.

{
  "options": [
    {
      "color": "red",
      "emotion": "sad",
      "condition2": "bad"
    },
    {
      "color": "green",
      "emotion": "happy",
      "condition2": "good"
    },
    {
      "color": "yellow",
      "emotion": "meh",
      "condition2": "neutral"
    }
  ],
  "condition1": "good"
}

Then Recursively copy the outer condition into each of the array objects and finally make a value setter to copy the matching object using jmespath:
myCondition.string = &{options[?condition2 == condition1]}

Still it would be interesting to know if this can be done directly without the recursive copying.

1 Like

Hi @kjetil

We are glad that you managed to get it worked by having a look at another topic in this forum.

As far as I know, unfortunately, this is the only shortest way to achieve your objective. The JMESPath filter expression (array[?x == y]) can only filter where x and y are properties within each array object or a static value like '123' or 'test'.

Hello everyone, I have attempted to compare the barCode value with the _bar value within the meta section. However, regardless of whether the values are the same or different, I consistently receive the same response.

{
“barCode”: “876545689”,
“meta”: [
{
“_bar”: “8765456890”
},
{
“_street”: “hjguu667”
}
]
}

Remember to first copy the barcode value into the children.
When the barcode is not the same you will get an empty array. When it’s equal, you will get that array object.

You can check this example:
export_20230608211654.ndjson (1.4 KB)