我想反转某些数据的键和值,其中值是数组,因此值数组的每个唯一元素都成为输出中的键,其值是一个数组,其中包含其值最初包含该元素的每个输入键.
举个例子,我有一些这样的数据:
[
{
"Id": "abc",
"Contents": [
"foo",
"bar"
]
},
{
"Id": "def",
"Contents": [
"foo",
"baz",
"ding"
]
},
{
"Id": "ghi",
"Contents": [
"bar",
"dang",
"baz"
]
}
]
我希望获得以下输出:
{
"foo": [
"abc",
"def"
],
"bar": [
"abc",
"ghi",
],
"baz": [
"def",
"ghi"
],
"ding": [
"def"
],
"dang": [
"ghi"
]
}
基于这个网站上的其他问题,我已经try 了以下方法,但我在使用reduce
的时候试图避免冲击结果.我知道我已经很接近了,我只是在努力处理嵌套的数据.
map(.Id as $Id
| .Contents
| map({key: ., value: [$Id]})
| from_entries
)
| reduce .[] as $item ({}; . * $item)
这段代码的问题在于,虽然它确实返回了我想要的 struct 中的数据,但它 destruct 了值.这就是它现在的输出:
{
"foo": [
"def"
],
"bar": [
"ghi"
],
"baz": [
"ghi"
],
"ding": [
"def"
],
"dang": [
"ghi"
]
}
我试过嵌套reduce
个调用,但都无济于事,我只是对语法不太熟悉.我可以用其他语言处理这件事,但我真的很想用JQ来做.我遗漏了什么?