Match keys with sibling object JSONATA

Viewed 347

I have an JSON object with the structure below. When looping over key_two I want to create a new object that I will return. The returned object should contain a title with the value from key_one's name where the id of key_one matches the current looped over node from key_two.

Both objects contain other keys that also will be included but the first step I can't figure out is how to grab data from a sibling object while looping and match it to the current value.

{
  "key_one": [
    {
      "name": "some_cool_title",
      "id": "value_one",
      ...
    }
  ],
  "key_two": [
    {
      "node": "value_one",
      ...
    }
  ],
}
2 Answers

This is a good example of a 'join' operation (in SQL terms). JSONata supports this in a path expression. See https://docs.jsonata.org/path-operators#-context-variable-binding

So in your example, you could write:

key_one@$k1.key_two[node = $k1.id].{
    "title": $k1.name
}

You can then add extra fields into the resulting object by referencing items from either of the original objects. E.g.:

key_one@$k1.key_two[node = $k1.id].{
    "title": $k1.name,
    "other_one": $k1.other_data,
    "other_two": other_data
}

See https://try.jsonata.org/--2aRZvSL

I seem to have found a solution for this.

[key_two].$filter($$.key_one, function($v, $k){
    $v.id = node
}).{"title": name ? name : id}

Gives:

[
  {
    "title": "value_one"
  },
  {
    "title": "value_two"
  },
  {
    "title": "value_three"
  }
]

Leaving this here if someone have a similar issue in the future.

Related