Overwrite the value of variable | x = x+1 | x= sum(x+1) #192
-
Dear All, I have a requirement to check the order of the input keys with the order of the data available in data.json example:
data.json
In this example the order of keys in the 2nd object of the input is not as expected and hence the result should be false . I have tried below approach but i couldn't do arithmetic operation to increment the value of a variable . package play
import data.orderofheader
import future.keywords.in
default ordercheck=false
ordercheck_result[message]{
headers:=input[_]
i:=0
j:=1
some key,_ in headers
not has_key(key, i)
i=sum({i, j}) #----------Its not working
#i=i+1 ----------Its not working
#i=i+j ----------Its not working
#z:=i+j ------it works but couldn't increment the z value further since reassigning different value is not possible
#message:=sprintf("index is %v and Key is %v",[z, key])
message:=sprintf("The value of the header '%v' in the given input is not in proper order ", [key])
}
has_key(key,i){
key==orderofheader[i]
} In General, if i assign a value to a variable say i:=0 then im not able to overwrite the value of the variable. On side Note: Is there a way to get the current index value of the key while using "some key, _ in headers" Could any of you advice on any workaround ? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
As @anderseknert pointed out in open-policy-agent/opa#4679 (comment), an object isn't ordered. However, for completeness sake, here's one way to check the ordering of something that is ordered, an array: package play
import future.keywords
ordering := ["apple", "banana", "capybara"] # the desired ordering
is_ordered(x) {
every idx, element in ordering {
x[idx].name == element
}
count(ordering) == count(x)
} else = false
test_correct = is_ordered([{"name": "apple"}, {"name": "banana"}, {"name": "capybara"}])
test_incorrect = is_ordered([{"name": "banana"}, {"name": "apple"}, {"name": "capybara"}])
test_short = is_ordered([{"name": "apple"}, {"name": "banana"}]) (On your original question there, you cannot overwrite values. What you can do is define values that depend on input, but you cannot update that value. That said, I think the need to overwrite a value is the Y of an XY problem.) |
Beta Was this translation helpful? Give feedback.
-
@srenatus Thanks for sharing . I agree to the point that the object is not an ordered collection. The alternative solution you have shared is evaluating the value of the object and not on key and the key remains same (as name) in your object."is_ordered([{"name": "apple"}, {"name": "banana"}, {"name": "capybara"}])" In my case , i need to compare keys and not values . |
Beta Was this translation helpful? Give feedback.
As @anderseknert pointed out in open-policy-agent/opa#4679 (comment), an object isn't ordered. However, for completeness sake, here's one way to check the ordering of something that is ordered, an array:
👉 play…