使用jq,如何将浅层对象数组的任意JSON编码转换为CSV?
这个网站上有很多关于特定数据模型的问答,这些数据模型对字段进行了硬编码,但是对于任何JSON,此问题的答案都应该有效,唯一的限制是它是具有标量属性的对象数组(无深度/复杂/子对象,如将它们展平是另一个问题)。结果应该包含一个标题行,给出字段名称。将优先考虑保留第一个对象的字段顺序的答案,但这不是必需的。结果可以用双引号将所有单元格括起来,或者仅将需要引用的单元格括起来(例如“ a,b”)。
例子
输入:
[ {"code": "NSW", "name": "New South Wales", "level":"state", "country": "AU"}, {"code": "AB", "name": "Alberta", "level":"province", "country": "CA"}, {"code": "ABD", "name": "Aberdeenshire", "level":"council area", "country": "GB"}, {"code": "AK", "name": "Alaska", "level":"state", "country": "US"} ]
可能的输出:
code,name,level,country NSW,New South Wales,state,AU AB,Alberta,province,CA ABD,Aberdeenshire,council area,GB AK,Alaska,state,US
可能的输出:
"code","name","level","country" "NSW","New South Wales","state","AU" "AB","Alberta","province","CA" "ABD","Aberdeenshire","council area","GB" "AK","Alaska","state","US"
输入:
[ {"name": "bang", "value": "!", "level": 0}, {"name": "letters", "value": "a,b,c", "level": 0}, {"name": "letters", "value": "x,y,z", "level": 1}, {"name": "bang", "value": "\"!\"", "level": 1} ]
可能的输出:
name,value,level bang,!,0 letters,"a,b,c",0 letters,"x,y,z",1 bang,"""!""",0
可能的输出:
"name","value","level" "bang","!","0" "letters","a,b,c","0" "letters","x,y,z","1" "bang","""!""","1"
json2csv
在stackoverflow.com/questions/57242240/…–