gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 19:28:18 26 4
gpt4 key购买 nike

给定一个 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"
}
}
输出看起来像这样。 header 可以硬编码。
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

关于json - 使用具有不同键的 jq 将 json 转换为 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68996590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com