如何将嵌套的JSON转换为逗号分隔的文件进行分析?以下是细节



需要像下面这样解析以下Json -

new.json

{
"name": "johnDoe",
"dept": 45,
"details": [
{
"salary": "76566",
"weight": "150",
"height": "160",
"sex": "male",
"country": "Usa",
"State": "NJ"
},
{
"salary": "76560",
"weight": "160",
"height": "180",
"sex": "male",
"country": "Usa",
"State": "NC"
}
]
}
{
"name": "DanLee",
"dept": 46,
"details": [
{
"salary": "76566",
"weight": "180",
"height": "160",
"sex": "male",
"country": "Usa",
"State": "NJ"
},
{
"salary": "76560",
"weight": "190",
"height": "180",
"sex": "male",
"country": "Usa",
"State": "NC"
},
{
"salary": "87888",
"weight": "170",
"height": "160",
"sex": "male",
"country": "Usa",
"State": "NY"
}
]
}

需要从上述Json格式中提取名称,权重和状态信息,并获得一个逗号分隔的文件以进行分析,如:

name,weight,State
johnDoe,150,NJ
johnDoe,160,NC
DanLee,180,NJ
DanLee,190,NC
DanLee,170,NY

我刚刚开始在Linux中使用Jq,并希望通过一步一步的解释来理解这种转换是如何完成的。

谢谢。

jq -r '.name as $name | .details[] | [$name, .weight, .State] | @csv' foo.json

给我:

"johnDoe","150","NJ"
"johnDoe","160","NC"
"DanLee","180","NJ"
"DanLee","190","NC"
"DanLee","170","NY"
击穿:

  • .name as $name请记住当前名称为$name
  • .details[]逐个展开细节数组
  • [$name, .weight, .State]为每个细节元素构建一个数组
  • @csv使用内置的CSV转换
  • -r:不再使用JSON字符串包装输出

相关内容

最新更新