我确实有一个格式的json(但有更多/更深的嵌套对象(
{
"Group": {
"Group1": {
"GroupA": {
"value": "#fffff",
"type": "color"
},
"GroupB": {
"value": "#c2c2c2",
"type": "color"
},
"GroupC": {
"Group_XY": {
"value": "#aw13ma",
"type": "color"
}
}
},
"Group2":{
"GroupA": {
"value": "#ff123f",
"type": "color"
},
"GroupB": {
"value": "#fffff",
"type": "color"
},
"GroupD": {
"value": "#ababab",
"type": "color"
}
},
"Group3": {
"GroupA": {
"value": "#fffff",
"type": "color"
},
"GroupC": {
"Group_XY": {
"value": "#12a3ma",
"type": "color"
}
},
"GroupD": {
"value": "#fffff",
"type": "color"
}
},
"Group4": {
"GroupA": {
},
"GroupB": {
"value": "#c2c2c2",
"type": "color"
},
"GroupE": {
"Group_XX": {
"Group_A1": {
"value": "#12a3ma",
"type": "color"
}
}
}
}
}
}
我想要实现的是一个csv/表输出进行比较:
第1组 | 第2组 | 第3组>第4组||||||
---|---|---|---|---|---|---|---|
组A | |||||||
集团B | |||||||
集团C | |||||||
组_XY | #aw13ma | #12a3ma | |||||
组D | |||||||
集团E | |||||||
集团_XX | |||||||
组_A1 | #12a3ma | ||||||
我不在乎工具堆栈
那么,为什么不使用jq呢?它可以轻松地转换JSON,甚至可以使用@csv
内置和--raw-output
(或-r
(选项生成您想要的输出格式。
.Group | to_entries | reduce (
.[] | (.value | paths(objects) as $p | [$p, getpath($p).value]) + [.key]
) as [$path, $value, $column] ({}; ."($path)"[$column] = $value)
| (keys | map(fromjson) | sort) as $paths
| ($paths | map(length) | max) as $width
| (map(keys[]) | unique) as $heads
| [(range($width) | null), $heads[]], ($paths[] as $path
| ($path | .[:-1] |= map(null)) + [range($path | $width - length) | null]
+ [."($path)"[$heads[]]]
) | @csv
,,,"Group1","Group2","Group3","Group4"
"GroupA",,,"#fffff","#ff123f","#fffff",
"GroupB",,,"#c2c2c2","#fffff",,"#c2c2c2"
"GroupC",,,,,,
,"Group_XY",,"#aw13ma",,"#12a3ma",
"GroupD",,,,"#ababab","#fffff",
"GroupE",,,,,,
,"Group_XX",,,,,
,,"Group_A1",,,,"#12a3ma"
演示
个人建议:为了更好的可读性,我会"合并";那些";空白";行,因为它们不提供额外的信息,同时组合(如果需要,还可以复制(行标题上的路径项。为此,将paths(objects)
扩展到paths(objects | has("value"))
,使其仅下降到有值的项目,并通过将($path | .[:-1] |= map(null))
更改为仅$path
:来揭示完整路径
.Group | to_entries | reduce (
.[] | (.value | paths(objects | has("value")) as $p | [$p, getpath($p).value]) + [.key]
) as [$path, $value, $column] ({}; ."($path)"[$column] = $value)
| (keys | map(fromjson) | sort) as $paths
| ($paths | map(length) | max) as $width
| (map(keys[]) | unique) as $heads
| [(range($width) | null), $heads[]], ($paths[] as $path
| $path + [range($path | $width - length) | null]
+ [."($path)"[$heads[]]]
) | @csv
,,,"Group1","Group2","Group3","Group4"
"GroupA",,,"#fffff","#ff123f","#fffff",
"GroupB",,,"#c2c2c2","#fffff",,"#c2c2c2"
"GroupC","Group_XY",,"#aw13ma",,"#12a3ma",
"GroupD",,,,"#ababab","#fffff",
"GroupE","Group_XX","Group_A1",,,,"#12a3ma"
演示