我有一个(字典?)JSON 文件,类似于:
{
"Salad": {
"name": "Dressing",
"good": true,
"status": true
},
"Data_XML": {
"name": "XML",
"good": false
},
"Functionality": {
"name": "FUNC",
"good": true
},
"Data_JSON": {
"name": "JSON",
"good": true,
"status": false
}
}
我正在寻找这样的 CSV 输出:
"title","good","name","status"
"Salad",true,"Dressing",true
"Data_XML",false,"XML",""
"Functionality",true,"FUNC",""
"Data_JSON",true,"JSON",false
什么我已经发现到目前为止使用的是这个......
jq -r '(map(keys_unsorted) | add | unique) as $cols | $cols, map(. as $row | $cols | map($row[.]))[] | @csv'
输出:
"good","name","status"
true,"Dressing",true
false,"XML",
true,"FUNC",
true,"JSON",false
我需要相当于沙拉、Data_XML、功能和 Data_JSON作为第一栏(未排序)以及相关数据。
至于“良好”、“姓名”、“状态”这些将是标头字段,因此需要动态检索,因为它们是随机的(每个数据集可能有 4 个,其他数据集可能有 10 个)。这是一个相对较大的文件,很难手动解析这些文件,将“标题”保留为第一个列标题项。“标题”,“好”,“名称”,“状态”,“某事”,“其他”,“随机”,“等”
我觉得我是如此接近......非常感谢任何帮助!
答案1
我认为这会起作用:
jq -r '["title","name","good","status"],(to_entries|.[]|
[.key,.value.good,.value.name,
(if .value.status == null then "" else .value.status end )]
)|@csv'
新版本更通用
jq -r ' to_entries as $row |
( ( map(keys_unsorted ) | add | unique ) as $cols |
( ["title" , $cols] | flatten) ,
( $row | .[] as $onerow | $onerow |
( [ .key , ( $cols |
map ($onerow.value[.] as $v | if $v == null then "" else $v end ) ) ]
| flatten ) ) ) | @csv '