open-policy-agentrego

OPA REGO deconstructing nested array


I got data something like this:

{
  "TENANT1":{ <-- Multiple tenants
    "SITE1":{ <-- Every tenant can have multiple sites
      "SITE1_DEVICE1":[ <-- Every site can have multiple devices
        "TEMP", <-- Just types
        "SET",
        "HUM"
      ],
      "SITE1_DEVICE2":[
        "TEMP"
      ]
    },
    "SITE2":{
      "SITE2_DEVICE1":[
        "TEMP",
        "HUM"
      ]
    }
  }
}

I want to list every device with types that given tenant is authorized for. This is what I tried:

test[devices] {
    devices = data["TENANT1"][_]
}

with result:

{
  "test":[
    {
      "SITE1_DEVICE1":["TEMP","SET","HUM" ],
      "SITE1_DEVICE2":["TEMP"]
    },
    {
      "SITE2_DEVICE1":["TEMP","HUM"]
    }
  ]
}

Is it somehow possible to have them all on the same level, not divided but it's sites, something like this:

{
  "test":[
      "SITE1_DEVICE1":["TEMP","SET","HUM" ],
      "SITE1_DEVICE2":["TEMP"],
      "SITE2_DEVICE1":["TEMP","HUM"]
  ]
}

Thanks in advance!


Solution

  • Please use the below rule:

    Rule:

    test[devices] := ret {
        some key, value in input.TENANT1[_]
        devices := key
        ret := value
    }
    

    Output:

    {
        "test": {
            "SITE1_DEVICE1": [
                "TEMP",
                "SET",
                "HUM"
            ],
            "SITE1_DEVICE2": [
                "TEMP"
            ],
            "SITE2_DEVICE1": [
                "TEMP",
                "HUM"
            ]
        }
    }