我在Windows 64位计算机上使用JQ 1.4。
以下是输入文件IP.txt
{
"results": [
{
"name": "Google",
"employees": [
{
"name": "Michael",
"division": "Engineering"
},
{
"name": "Laura",
"division": "HR"
},
{
"name": "Elise",
"division": "Marketing"
}
]
},
{
"name": "Microsoft",
"employees": [
{
"name": "Brett",
"division": "Engineering"
},
{
"name": "David",
"division": "HR"
}
]
}
]
}
{
"results": [
{
"name": "Amazon",
"employees": [
{
"name": "Watson",
"division": "Marketing"
}
]
}
]
}
文件包含两个"results"
。第一个结果包含2家公司的信息:Google
和Microsoft
。第二个结果包含Amazon
的信息。
我想将此JSON转换为具有公司名称和员工姓名的csv文件。
"Google","Michael"
"Google","Laura"
"Google","Elise"
"Microsoft","Brett"
"Microsoft","David"
"Amazon","Watson"
我可以写下面的脚本:
jq -r "[.results[0].name,.results[0].employees[0].name]|@csv" IP.txt
"Google","Michael"
"Amazon","Watson"
有人可以指导我编写脚本而无需对索引值进行硬编码吗?
脚本应该能够生成任意数量results
的输出以及任意数量公司的每个共同信息。
我尝试使用下面的脚本,它不会产生预期的输出:
jq -r "[.results[].name,.results[].employees[].name]|@csv" IP.txt
"Google","Microsoft","Michael","Laura","Elise","Brett","David"
"Amazon","Watson"
答案 0 :(得分:3)
您需要先将结果压缩到公司和员工姓名行。然后,您可以转换为csv行。
map(.results | map({ cn: .name, en: .employees[].name } | [ .cn, .en ])) | add[] | @csv
由于您有输入流,因此您必须将其插入(-s
)。由于您要输出csv,您将要使用原始输出({{1 }})。