如何仅使用 jq 将嵌套的 JSON 转换为 CSV [英] How to convert nested JSON to CSV using only jq
问题描述
我关注了 json,
{
"A": {
"C": {
"D": "T1",
"E": 1
},
"F": {
"D": "T2",
"E": 2
}
},
"B": {
"C": {
"D": "T3",
"E": 3
}
}
}
我想把它转换成csv如下,
I want to convert it into csv as follows,
A,C,T1,1
A,F,T2,2
B,C,T3,3
输出描述:父键将被打印,直到我到达叶子子节点.一旦我到达叶子孩子,打印它的价值.
Description of output: The parents keys will be printed until, I've reached the leaf child. Once I reached leaf child, print its value.
我试过,但没有成功,
cat my.json |jq -r '(map(keys) | add | unique) as $cols |map(.as $row | $cols | map($row[.])) as $rows |$行[] |@csv'
cat my.json | jq -r '(map(keys) | add | unique) as $cols | map(. as $row | $cols | map($row[.])) as $rows | $rows[] | @csv'
它给我一个错误.
我无法对父键进行硬编码,因为实际的 json 有太多记录.但是json的结构是类似的.我错过了什么?
I can't hardcode the parent keys, as the actual json has too many records. But the structure of the json is similar. What am I missing?
推荐答案
有些要求不清楚,但以下解决了对问题的一种解释:
Some of the requirements are unclear, but the following solves one interpretation of the problem:
paths as $path
| {path: $path, value: getpath($path)}
| select(.value|type == "object" )
| select( [.value[]][0] | type != "object")
| .path + ([.value[]])
| @csv
(此程序可以优化,但此处的演示旨在使单独的步骤清晰.)
(This program could be optimized but the presentation here is intended to make the separate steps clear.)
调用:
jq -r -f leaves-to-csv.jq input.json
输出:
"A","C","T1",1
"A","F","T2",2
"B","C","T3",3
未加引号的字符串
为了避免字符串周围的引号,您可以将上面管道的最后一个组件替换为:
Unquoted strings
To avoid the quotation marks around strings, you could replace the last component of the pipeline above with:
join(",")
这篇关于如何仅使用 jq 将嵌套的 JSON 转换为 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!