简体   繁体   中英

Rego - Combine Values of Case Sensitive Keys from json like abc, ABc to single lowercase key abc

I've below json as an input:

{
    "data": {
        "abc": 123,
        "Abc": 345,
        "bcd": 789
    }
}

I want the result like:

{
    "data": {
        "abc": "123,345",
        "bcd": "789"
    }
}

ie case insensitive key and the values as list or comma-separated String.

For below code block, it's giving error like

policy.rego:3: eval_conflict_error: object keys must be unique

result := {lower(key): input.data[key] | count(key)>0}

Here's a rego playground link.

I'm really newbie to rego and not able to understand if this can be done. Any help would be really appreciated. Thanks!

This is definitely doable in Rego, but it does require getting comfortable with array comprehensions first!

package stackoverflow.example

result[k] := v {
    # Find a value `i`, and assign `k` to be that value lowercased.
    some i
    input.data[i]
    k := lower(i)

    # We use an array comprehension to generate a list.
    # A separate "some" variable is needed here for the comprehension,
    # because `i` has already been assigned a fixed value.
    some j
    values := [format_int(x, 10) | x := input.data[j]; lower(j) == k]
    v := concat(",", values)
}

Interactive Rego Playground link

You can code-golf this down a bit as well, although it's a bit more cluttered:

golfed_version[k] := v {
    some i, j
    input.data[i]
    k := lower(i)
    v := concat(",", [format_int(x, 10) | x := input.data[j]; lower(j) == k])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM