Search code examples
open-policy-agentrego

Transform ["a=b","c=d","e=f"] to {"a":"b","c":"d","e":"f"} in rego


I have an array as defined below

        ["dev=devA",
        "instance=instanceA",
        "domain=domainA",
        "namespace=namespaceA",
        "service=serviceA"]

I want an object in kv format, as defined below

        {"dev"="devA",
        "instance"="instanceA",
        "domain"="domainA",
        "namespace"="namespaceA",
        "service="serviceA"}

I tried to {x | x := split(str, "/")[_]} used sprintf to print out. However, the sprintf want array[any], now the input is set[string]


Solution

  • You could use an object comprehension:

    package policy
    
    arr := ["dev=devA",
            "instance=instanceA",
            "domain=domainA",
            "namespace=namespaceA",
            "service=serviceA"]
            
    obj := {k: v |
        item := arr[_]
        [k, v] := split(item, "=")
    }
    

    Full example at the Rego Playground.