使用不同键的jq将json转换为csv



给定一个JSON对象数组,我想输出一个CSV,其中一行包含每个对象键,其他行基于每个对象值。

输入json为:

{
"PCID000": {
"OSmodle": "LINUX",
"IEversion": "2.15.0",
"hardwareUSB": [
"Card reader",
"keyboard"
],
"OrderStatus": "01"
},
"PCID999": {
"OSmodle": "LINUX",
"OSversion": "4.0",
"hardwareUSB": [],
"OrderStatus": "01"
}
}

输出看起来像这样。头文件可以硬编码

PCID,OSmodle,OSversion,IEversion,hardwareUSB, OrderStatus
"PCID000","LINUX",,"2.15.0","Card reader&keyboard","01"
"PCID999","LINUX","4.0",,"01

可以使用to_entries函数将对象(如{"a": 1, "b": 2})转换为键值对象(如[{"key": "a", "value": 1}, {"key": "b", "value": 2}])数组。然后在此基础上进行映射,选择感兴趣的键和部分值

jq脚本看起来像这样:

to_entries | map([
.key,
.value.OSmodle,
.value.OSversion,
.value.IEversion,
(.value.hardwareUSB | join("&")),
.value.OrderStatus])
| ["PCID", "OSmodle", "OSversion", "IEversion", "hardwareUSB", "OrderStatus"], .[]
| @csv

输出(含-r):

"PCID","OSmodle","OSversion","IEversion","hardwareUSB","OrderStatus"
"PCID000","LINUX",,"2.15.0","Card reader&keyboard","01"
"PCID999","LINUX","4.0",,"","01"

jqplay

相关内容

  • 没有找到相关文章

最新更新