问题描述
我正在尝试转换一个看起来像这样的对象:
I'm trying to convert an object that looks like this:
{
"123" : "abc",
"231" : "dbh",
"452" : "xyz"
}
对于如下所示的csv:
To csv that looks like this:
"123","abc"
"231","dbh"
"452","xyz"
我更喜欢使用命令行工具 jq ,但似乎无法确定找出如何做作业.我设法用jq '. | keys' test.json
来获取密钥,但不知道下一步该怎么做.
I would prefer to use the command line tool jq but can't seem to figure out how to do the assignment. I managed to get the keys with jq '. | keys' test.json
but couldn't figure out what to do next.
问题是您无法使用@csv
将像这样的k:v对象直接转换为csv.它必须是一个数组,所以我们需要先转换为数组.如果键被命名,这很简单,但是它们是动态的,因此并不是那么容易.
The problem is you can't convert a k:v object like this straight into csv with @csv
. It needs to be an array so we need to convert to an array first. If the keys were named, it would be simple but they're dynamic so its not so easy.
推荐答案
尝试使用此过滤器:
to_entries[] | [.key, .value]
-
to_entries
将对象转换为键/值对象的数组.[]
将数组分解为数组中的每个项目 - 然后对于每个项目,将其隐藏到包含键和值的数组中.
to_entries
converts an object to an array of key/value objects.[]
breaks up the array to each of the items in the array- then for each of the items, covert to an array containing the key and value.
这将产生以下输出:
[
"123",
"abc"
],
[
"231",
"dbh"
],
[
"452",
"xyz"
]
然后,您可以使用@csv
过滤器将行转换为CSV行.
Then you can use the @csv
filter to convert the rows to CSV rows.
$ echo '{"123":"abc","231":"dbh","452":"xyz"}' | jq -r 'to_entries[] | [.key, .value] | @csv'
"123","abc"
"231","dbh"
"452","xyz"
这篇关于如何将对象映射到数组,以便可以将其转换为csv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!