【发布时间】:2015-04-21 06:47:10
【问题描述】:
我在 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"
【问题讨论】: