将[“a=b”,”c=d”,”e=f”] 转换为 {“a”:”b”,”c”:”d”,”e”:”f”} 在 rego 中。

huangapple go评论81阅读模式
英文:

Transform ["a=b","c=d","e=f"] to {"a":"b","c":"d","e":"f"} in rego

问题

I have an array as defined below:

  1. ["dev=devA",
  2. "instance=instanceA",
  3. "domain=domainA",
  4. "namespace=namespaceA",
  5. "service=serviceA"]

I want an object in kv format, as defined below:

  1. {"dev"="devA",
  2. "instance"="instanceA",
  3. "domain"="domainA",
  4. "namespace"="namespaceA",
  5. "service"="serviceA"}

I tried to {x | x := split(str, "=")[_]} used sprintf to print out. However, the sprintf wants array[any], but the input is set[string].

英文:

I have an array as defined below

  1. ["dev=devA",
  2. "instance=instanceA",
  3. "domain=domainA",
  4. "namespace=namespaceA",
  5. "service=serviceA"]

I want an object in kv format, as defined below

  1. {"dev"="devA",
  2. "instance"="instanceA",
  3. "domain"="domainA",
  4. "namespace"="namespaceA",
  5. "service="serviceA"}

I tried to {x | x := split(str, "/")[_]} used sprintf to print out. However, the sprintf want array[any], now the input is set[string]

答案1

得分: 0

你可以使用对象理解(Object Comprehension):

  1. package policy
  2. arr := ["dev=devA",
  3. "instance=instanceA",
  4. "domain=domainA",
  5. "namespace=namespaceA",
  6. "service=serviceA"]
  7. obj := {k: v |
  8. item := arr[_]
  9. [k, v] := split(item, "=")
  10. }

完整示例请查看Rego Playground

英文:

You could use an object comprehension:

  1. package policy
  2. arr := ["dev=devA",
  3. "instance=instanceA",
  4. "domain=domainA",
  5. "namespace=namespaceA",
  6. "service=serviceA"]
  7. obj := {k: v |
  8. item := arr[_]
  9. [k, v] := split(item, "=")
  10. }

Full example at the Rego Playground.

huangapple
  • 本文由 发表于 2023年4月11日 03:03:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定