将嵌套数组中已知的键组合为该数组的对象。

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

Combine known keys external to nested array as objects of that array

问题

[
  {
    "some_key": "x",
    "all_foo": [
      {
        "foo_id": 123,
        "foo_name": "bar_1"
      },
      {
        "foo_id": 456,
        "foo_name": "bar_2"
      }
    ]
  }
]
英文:

I have an input JSON that looks like this:

[
  {
    "some_key": "x",
    "foo_id": 123,
    "foo_name": "bar_1",
    "all_foo": [
      {
        "foo_id": 456,
        "foo_name": "bar_2"
      }
    ]
  }
]

The requirement is to collapse foo_id and foo_name (this is known ahead of time) as objects under all_foo, so that output is:

[
  {
    "some_key": "x",
    "all_foo": [
	  {
	    "foo_id": 123,
        "foo_name": "bar_1"
	  },
      {
        "foo_id": 456,
        "foo_name": "bar_2"
      }
    ]
  }
]

Order on all_foo does not matter.

What I tried so far:

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "all_foo": {
        "*": "&",
        "&1": "[&1].&"
      }
    }
  }
]

答案1

得分: 1

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

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "some_key": "&",
        "all_foo": {
          "@1,foo_name": "&1[0].foo_name",
          "@1,foo_id": "&1[0].foo_id",
          "*": "&1[]"
        }
      }
    }
  }
]

或者你也可以使用以下的规则:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "&", // 仅匹配 "some_key" 属性的其他情况
        "foo_*": "all_foo.&", // 匹配以 foo_ 开头的所有属性
        "all_foo": {
          "*": "&1"
        }
      }
    }
  }
]

在这两种规则中,所有的键值对都是从树的相同级别调用的。

英文:

You can use the following shift transformation spec

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "some_key": "&",
        "all_foo": {
          "@1,foo_name": "&1[0].foo_name",
          "@1,foo_id": "&1[0].foo_id",
          "*": "&1[]"
        }
      }
    }
  }
]

or alternatively use the following one

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "&", // else case in which only "some_key" attribute is matched
        "foo_*": "all_foo.&", // all attributes those start with foo_
        "all_foo": {
          "*": "&1"
        }
      }
    }
  }
]

where all key-value pairs are called from the same level of the tree

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

发表评论

匿名网友

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

确定