How to convert nested JSON to CSV using only jq

守給你的承諾、 提交于 2019-12-04 19:06:25

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.)

Invocation:

jq -r -f leaves-to-csv.jq input.json

Output:

"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(",")

Here is a solution using tostream and group_by

    [
        tostream
      | select(length == 2)            # e.g. [["A","C","D"],"T1"]
      | .[0][:-1] + [.[1]]             #      ["A","C","T1"]
    ]
    | group_by(.[:-1])                 #    [[["A","C","T1"],["A","C",1]],...
    | .[]                              #     [["A","C","T1"],["A","C",1]]
    | .[0][0:2] + map(.[-1]|tostring)  #      ["A","C","T1","1"]
    | join(",")                        #       "A,C,T1,1"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!