使用 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"
Input:
[
{"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"