使用 jq 合并具有公共键的对象的属性值
我有一个具有 2 个属性的对象数组,例如“key”和“value”:
[
{key: 1, value: a},
{key: 2, value: b},
{key: 1, value: c}
]
现在,我想将具有相同“key”属性值的对象的“value”属性的值合并。那就是前面的数组被转换成:
[
{key: 1, value: [a, c]},
{key: 2, value: [b]}
]
我尝试了类似的东西:
$ echo '[{"key": "1", "val": "a"}, {"key": "2", "val": "b"}, {"key": "1", "val": "c"}]' | jq '. | group_by(.["key"]) | .[] | reduce .[] as $in ({"val": []}; {"key": $in.key, "val": [$in.val] + .["val"]})'
但它触发了 jq 语法错误,我不知道为什么。我被困住了。
有什么想法吗?
谢谢
B
I have an array of objects with 2 properties, say "key" and "value":
[
{key: 1, value: a},
{key: 2, value: b},
{key: 1, value: c}
]
Now, I would like to merge the values of the "value" properties of objects with the same "key" property value. That is the previous array is transformed into:
[
{key: 1, value: [a, c]},
{key: 2, value: [b]}
]
I tried something like:
$ echo '[{"key": "1", "val": "a"}, {"key": "2", "val": "b"}, {"key": "1", "val": "c"}]' | jq '. | group_by(.["key"]) | .[] | reduce .[] as $in ({"val": []}; {"key": $in.key, "val": [$in.val] + .["val"]})'
But it triggers a jq syntax error and I have no idea why. I am stuck.
Any idea ?
Thanks
B
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用
reduce
的方法可以清理为Demo
另一种使用
的方法地图
将是演示
Your approach using
reduce
could be sanitized toDemo
Another approach using
map
would beDemo