You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 07:35:27