简体   繁体   English

Rego - 将来自 json 的区分大小写键的值(如 abc、ABc)组合为单个小写键 abc

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

I've below json as an input:我将 json 作为输入:

{
    "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 policy.rego:3: eval_conflict_error: object 密钥必须是唯一的

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

Here's a rego playground link.这是一个 rego 游乐场链接。

I'm really newbie to rego and not able to understand if this can be done.我真的是 rego 的新手,无法理解是否可以做到这一点。 Any help would be really appreciated.任何帮助将非常感激。 Thanks!谢谢!

This is definitely doable in Rego, but it does require getting comfortable with array comprehensions first!这在 Rego 中绝对可行,但它确实需要先熟悉数组理解

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交互式 Rego 游乐场链接

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])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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