我知道jq可以实现这一点,但是增加了复杂性。 json对象中的一个字段是字符串数组。我们如何使用jq来处理这个问题?
{
"var": 1,
"section": ["1","2","3"],
"x": "test1"
},
{
"var": 2,
"section": ["2","3","4"],
"x": "test2"
},
{
"var": 3,
"section": ["3","4","5"],
"x": "test3"
},
我们如何制作这样的CSV输出?
var,section,x
"1","[1,2,3]","test1"
"2","[2,3,4]","test2"
"3","[3,4,5]","test3"
我想在jq参数中使用JSON.stringify。
答案 0 :(得分:2)
需要注意的是,你必须小心你想要的东西,并假设输入是一个对象数组,如下所示:
.[]
| [.[]
| if type == "array" then map(tonumber? // .) else . end
| tostring]
| @csv
生成所需的输出,标题行除外。
(如果数组内容无法转换为数字,“tonumber?//。”可以避免错误。)
这是一个变体,(a)为第一个对象中的所有键生成一行标题,无论它们是什么; (b)对于重新排序对象内的密钥是健全的:
. as $in
| ($in[0] | keys_unsorted) as $h
| ($h,
( $in[]
| ( [range(0; $h|length) as $i | getpath( [$h[$i]] )]
| map(if type == "array" then map(tonumber? // .) else . end)
| map(tostring) ) ))
| @csv
在tocsv.jq和input.json中输入:
$ jq -r -f tocsv.jq input.json
"var","section","x"
"1","[""a"",2,3]","test1"
"2","[2,3,4]","test2"
"3","[3,4,5]","test3"