问题描述
输入
{"key1": ["value1", "value2"], "key2": ["value3"]}
所需的输出
key1, value1
key1, value2
key2, value3
很难找到jq命令来实现这一目标...我尝试过使用map,as,to_entries过滤器以各种组合但没有运气.
Having a hard time figuring out jq command to achieve this... I have tried map, as, to_entries filters in various combinations but no luck.
推荐答案
我删除了JSON对象周围的多余括号,以使其成为有效JSON.因此,从此开始:
I removed the extra pair of brackets around your JSON object in order to make it a valid JSON. So, starting with this:
{
"key1": [ "value1", "value2" ],
"key2": [ "value3" ]
}
我们应用to_entries
,这可以为我们提供:
We apply to_entries
, which gives us this:
[
{
"key": "key1",
"value": [ "value1", "value2" ]
},
{
"key": "key2",
"value": [ "value3" ]
}
]
然后,我们对每个这些条目进行map
并扩展(c2)数组(c2),为其每个元素(map({key, value: .value[]})
)创建一个单独的对象.这给了我们:
Then, we map
each of those entries and we spread ([]
) the .value
array, creating a separate object for each of its elements (map({key, value: .value[]})
). This gives us:
[
{
"key": "key1",
"value": "value1"
},
{
"key": "key1",
"value": "value2"
},
{
"key": "key2",
"value": "value3"
}
]
在那之后,对于每个对象,我们需要一个带有其值的数组,因为这是@csv
过滤器所期望的.只是映射到数组对象,如map([.key, .value])
所示,这为我们提供了:
After that, for each of those objects, we want an array with its values, since that's what the @csv
filter expects. That's just mapping to an array object, as in map([.key, .value])
, which gives us:
[
[ "key1", "value1" ],
[ "key1", "value2" ],
[ "key2", "value3" ]
]
最后,我们扩展([]
)数组数组(因为@csv
需要单独的数组),然后将@csv
用管道传递给它.完整的脚本如下所示:
And, finally, we spread ([]
) the array of arrays (since @csv
expects individual arrays) and we pipe @csv
to it. The full script looks as follows:
jq -r 'to_entries | map({key, value: .value[]}) | map([.key, .value])[] | @csv' test.json
及其输出:
"key1","value1"
"key1","value2"
"key2","value3"
这篇关于使用jq将json映射转换为csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!