我有一个JSON文件:
{
"ClassIdentifier": "consumer-leads",
"StateMode": "txt-2300",
"StateGroups": []
}
{
"ClassIdentifier": "main",
"StateMode": null,
"StateGroups": [
{
"Status": "active",
"StateGroupName": "default"
},
{
"Status": "active",
"StateGroupName": "brown-space"
},
{
"Status": "active",
"StateGroupName": "txt-hosts"
}
]
}
{
"ClassIdentifier": "paid-media",
"StateMode": "txt-2300",
"StateGroups": []
}
{
"ClassIdentifier": "reports",
"StateMode": null,
"StateGroups": [
{
"Status": "active",
"StateGroupName": "txt-hosts"
},
{
"Status": "active",
"StateGroupName": "grey-space"
},
{
"Status": "active",
"StateGroupName": "default"
}
]
}
我需要的输出:
consumer-leads,txt-2300,null
main,null,brown-space|default|txt-hosts
paid-media,txt-2300,null
reports,null,default|grey-space|txt-hosts
请注意,状态组(如果存在)将按照StateGroupName排序,然后转换为由竖线分隔的值字符串。
我尝试过的方法只能得到部分结果,但并不能完全胜任这项工作。
cat json_file |
jq -r '[ .ClassIdentifier,
.StateMode,
.StateGroups[]
]'
cat json_file |
jq -r '{ ClassIdentifier,
StateMode
} +
( .StateGroups[] | { StateGroupName, Status } )
'
cat json_file |
jq -r ' [ .ClassIdentifier,
.StateMode,
.StateGroups |= sort_by( .StateGroupName )
]'
更新:我们必须使用JQ 1.3,请在回复中牢记这一点。