How to querying from two list of objects in jsonata?

Viewed 36

I am trying to query a json through Jsonata but I dont know how to do it.

This is what I have:

{
  "first-array": [
    {
      "param1": {
        "status": "SUCCESS"
      }
    },
    {
      "param2": {
        "status": "FAILURE"
      }
    },
    {
      "param3": {
        "status": "SUCCESS"
      }
    }
  ],
  "second-array": [
    {
      "param1": {
        "attribute1": "1",
        "attribute2": "2"
      }
    },
    {
      "param2": {
        "attribute3": "3",
        "attribute4": "4"
      }
    },
    {
      "param3": {
        "attribute5": "5",
        "attribute6": "6"
      }
    }
  ]
}

This is what I want. filter by SUCCESS status and retrieve only the attributes. For instance:

[
  {
    "param1": {
      "attribute1": "1",
      "attribute2": "2"
    }
  },
  {
    "param3": {
      "attribute5": "5",
      "attribute6": "6"
    }
  }
]

I have tried several things during this week, but I did not reach any way to proceed. Trying with merge functions, overwrite the entire value, instead of append. Trying to filter with something like first-array.*[status = "SUCCESS"] deletes the key where is the content.

Thank you. BR,

2 Answers

I think you can utilize $each function to convert your first-array into a utilizable map for filtering your second-array, something like this: https://stedi.link/qEzDJFm

Based on your idea to use something like first-array.*[status = "SUCCESS"] here is a solution that should have linear complexity.

(
  $successes := $.`first-array`[*.status = "SUCCESS"] ~> $keys();
  $attributes := $.`second-array` ~> $filter(function($v) { $v ~> $keys() in $successes });
  [$attributes[]]
)

https://stedi.link/VmFVNe0

EDIT

This solution offers the benefit that duplicate entries in first-array do not change the result. See https://stedi.link/sn3OUW5 where { "param1": { "status": "SUCCESS" } } exists twice.

Related