Search code examples
open-policy-agent

Loop through a nested json object in OPA


I am very new to OPA and trying to loop through the below input data

input = 
"data":{
    "list":[
        {"Name": "abc", "Status": "Done"},
        {"Name": "def", "Status": "Done"},
        {"Name": "ghi", "Status": "pending"},
        {"Name": "jkl", "Status": ""},
        {"Name": "mno", "Status": null},
    ]
}

and return two lists based on that input, one list that would return the names of all objects that has the status as 'Done' and another list with status not equal to 'Done', here is the rego code I was trying, I used somewhat python syntax to convey the code as I was not sure how the opa syntax would look like

package play
default done_list := []
default other_list := []

done_list {
  some i
  input.data.list[i].Status == "Done"
  done_list.append(input.data.list[i].Name) #python syntax and looking for something similar in opa
}

other_list{
  some j
  input.data.list[j].Status != "Done"
  other_list.append(input.data.list[j].Name)
}

#or maybe use a list comprehension like this?
#not even sure if this makes sense but ...

done_list = [x.Name | x := input.data.list[_]; x.Status = "Done"]
other_list = [x.Name | x := input.data.list[_]; x.Status != "Done"]

test_return{
   "done_list": done_list,
   "other_list": other_list
}

and the output I'm looking for is something like

{
"done_list": ["abc", "def"],
"other_list": ["ghi","jkl","mno"]
}

Any help is greatly appreciated. Thanks in advance.


Solution

  • I think you're best to use a list comprehension as you guessed :)

    package play
    
    doneStatus := "Done"
    
    result := {
        "done_list": [e |
            item := input.data.list[_]
            item.Status == doneStatus
            e := item.Name
        ],
        "other_list": [e |
            item := input.data.list[_]
            item.Status != doneStatus
            e := item.Name
        ],
    }
    
    

    I've created a Rego playground which shows this: https://play.openpolicyagent.org/p/dBKUXFO3v2