JSONata: Extract fields by partial name

490 Views Asked by At

I have a json with attribute names that start with some prefixes I need to ignore, and end with the actual field name:

{
    "context": {
        "values": {
            "group1:0:foo": "08119037",
            "group1:0:checkbox": [
                "2",
                "3"
            ]
        }
    }
}

I can extract the exact field group1:0:foo, but not "the field that ends with :foo":

{
    "foo": context.values.`group1:0:foo`
}

In the JSONata exerciser: https://try.jsonata.org/uqDfozN8r

2

There are 2 best solutions below

0
On BEST ANSWER

Solution by shrickus:

$spread(context.values)[$match($keys($)[0], /.*:foo/)]  {
    $keys($)[0].$split(":")[2]: $.*
}

-> Accepted answer because it avoids the lookup.

0
On

One possible solution: https://try.jsonata.org/9vruWw6HR

{
  "foo": $lookup(context.values, context.values.$keys()[$contains($, 'foo')])
}

Result:

{
  "foo": "08119037"
}