如何用jq遍历拆分后的JSON数组并生成指定格式CSV输出
使用jq处理JSON生成指定格式CSV
输入JSON
[ { "body": [ { "title": "topinfo", "longText": "item1|details item 1|details sdfdfdfd ||details gbgfgghmhjmh||details 5348786" }, { "title": "topinfo", "longText": "item2|details item 2|details sdfdfdfd ||details gbgfgghmhjmh||details 9784561" } ] } ]
当前使用的jq命令
jq '.[] | [.body[] | {longText,title} ] | to_entries | map( (.value.level = "\(1+.key)" ) | .value) | .[] | [.title,.level,(.longText|split("|"))] '
当前执行结果
[ "topinfo", "1", [ "item1", "details item 1", "details sdfdfdfd", "", "details gbgfgghmhjmh", "", "details 5348786" ] ] [ "topinfo", "2", [ "item2", "details item 2", "details sdfdfdfd", "", "details gbgfgghmhjmh", "", "details 9784561" ] ]
期望输出格式
topinfo;1;1;item1 topinfo;1;2;details item 1 topinfo;1;3;details sdfdfdfd topinfo;1;4;details gbgfgghmhjmh topinfo;1;5;details 5348786 topinfo;2;1;item2 topinfo;2;2;details item 2 topinfo;2;3;details sdfdfdfd topinfo;2;4;details gbgfgghmhjmh topinfo;2;5;details 9784561
解决方案
使用以下jq命令可以直接生成期望的CSV格式输出:
jq -r '.[] | .body[] | to_entries | map(.value.item_level = (1 + .key) | .value) | .[] | (.longText | split("|") | map(select(length > 0)) | to_entries | map([.title, (.item_level | tostring), (1 + .key | tostring), .value] | join(";"))) | .[]'
命令说明
.[] | .body[]:遍历最外层数组以及内部的body数组元素to_entries | map(.value.item_level = (1 + .key) | .value):给每个body元素添加层级序号(即你需要的1、2).longText | split("|") | map(select(length > 0)):拆分longText为数组,并过滤掉拆分产生的空字符串to_entries | map([.title, (.item_level | tostring), (1 + .key | tostring), .value] | join(";")):遍历拆分后的元素,给每个元素添加子序号,再将标题、层级序号、子序号、元素内容用分号拼接成单行-r参数:让jq输出原始字符串,而非JSON格式的字符串
内容的提问来源于stack exchange,提问作者shepi
相关产品推荐
相关产品推荐

