JSONata $filter

I posted here about a merge expression I was attempting to get working and received an answer. However, I notice that the match expression includes all records for Obj1 regardless of whether there is a matching key or not. I only want to return records that match and return no records in the output that don't match on the key.

I have read up on the filter function and tried to apply it to this scenario but it is not working. I also tried chatGPT and it also gave a answer that is invalid, according to JSONata.org and the test function on the change node, "Expected ")", got ";""

Input:

{"payload":[
        {
            "Obj1": [
                {
                    "Datetime": "2020-04-03 01:21:07.650",
                    "ID": "00001",
                    "code": "WAXXNNNX"
                },
                {
                    "Datetime": "2020-04-03 01:21:07.650",
                    "ID": "00002",
                    "code": "CAXXNNNX"
                }
            ]
        },
        {
            "Obj2": [
                {
                    "X102": "Y",
                    "X116": "N",
                    "X435": "00001"
                },
                {
                    "X102": "Y",
                    "X116": "Y",
                    "X435": "00002"
                }
            ]
        }
    ]}

Expression:

$$.payload[0].Obj1[$filter(Obj1, 
    $Obj2 := $$.payload[1].Obj2[$.X435 = $.ID];
    $Obj2 != null
).(
    {
        'ID': $.ID,
        'Datetime': $.Datetime,
        'Code': $.code,
        'X102_ZipSuffixFlag': $Obj2.X102,
        'X116_TerminationIDFlag': $Obj2.X116
    }
)]

Any help is appreciated, thanks!

You could just check Obj2 contains a match, then only return the new object if true.
e.g.

[$$.payload[0].Obj1@$Obj1.(
   $Obj2 := $$.payload[1].Obj2[$.X435 = $Obj1.ID];
   $exists($Obj2) ? {
       'ID': $Obj1.ID,
       'Datetime': $Obj1.Datetime,
       'Code': $Obj1.code,
       'X102_ZipSuffixFlag': $Obj2.X102,
       'X116_TerminationIDFlag': $Obj2.X116     
   } 
)]

[edit]
To satisfy my curiosity i decided to see if you could use a ternary conditional on a variable binding, and it turns out you can, so the $exists() is not required.
e.g.

[$$.payload[0].Obj1@$Obj1.(
   $Obj2 := $$.payload[1].Obj2[$.X435 = $Obj1.ID] ? {
       'ID': $Obj1.ID,
       'Datetime': $Obj1.Datetime,
       'Code': $Obj1.code,
       'X102_ZipSuffixFlag': $Obj2.X102,
       'X116_TerminationIDFlag': $Obj2.X116     
   } 
)]

Works also.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.