将一个键分配为兄弟数组的所有元素的键。

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

Assign a key as key to all elements of a sibling array

问题

{
"some_key": "x",
"another_key": "y",
"all_foo": [
{
"foo_id": 123,
"foo_name": "bar1"
},
{
"foo_id": 123,
"foo_name": "bar2"
}
]
}

英文:

I have an input JSON like this:

{
  "some_key": "x",
  "another_key": "y",
  "foo_id": 123,
  "all_foo": [
    {
      "foo_name": "bar1"
    },
    {
      "foo_name": "bar2"
    }
  ]
}

I'm looking for an output JSON like this:

{
  "some_key": "x",
  "another_key": "y",
  "all_foo": [
    {
      "foo_id": 123,
      "foo_name": "bar1"
    },
    {
      "foo_id": 123,
      "foo_name": "bar2"
    }
  ]
}

What I tried so far:

[
  {
    "operation": "shift",
    "spec": {
      "all_foo": {
        "*": {
          "*": "[&1].&",
          "@(2,foo_id)": "[&1].foo_id"
        }
      }
    }
  }
]

This works for all_foo. But I'm unable to keep some_key and another_key.

答案1

得分: 1

你可以使用以下的 shift 转换规则:

[
  {
    "operation": "shift",
    "spec": {
      "some*|ano*": "&", // "some_key" 或(pipe) "another_key"(* 是补充的,例如,键名以"some"或"ano"开头)
      "all_foo": {
        "*": {
          "@2,foo_id": "&2[&1].foo_id",
          "*": "&2[&1].&"
        }
      }
    }
  }
]

其中

  • "some*|ano*": "&" 表示外部属性的复制,除了 foo_id

  • &2 代表向上遍历两层,并抓取字面意义上的 all_foo 以形成一个名为 all_foo 的数组

英文:

You can use the following shift transformation spec

[
  {
    "operation": "shift",
    "spec": {
      "some*|ano*": "&", // "some_key" or(pipe) "another_key"(* is complementary, eg. key names start with "some" or "ano")
      "all_foo": {
        "*": {
          "@2,foo_id": "&2[&1].foo_id",
          "*": "&2[&1].&"
        }
      }
    }
  }
]

where

  • "some*|ano*": "&" represents replication of the outer attributes except for foo_id

  • &2s represent going two levels up the tree, and grabbing the literal all_foo in order to form an array called all_foo

huangapple
  • 本文由 发表于 2023年3月7日 20:31:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661996.html
匿名

发表评论

匿名网友

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

确定