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

如何通过Linux CLI将指定JSON转换为目标格式的CSV/格式化输出?

用CLI实现JSON转指定格式CSV/表格输出

需求实现方案

完全可以通过纯CLI命令完成,不需要依赖中间文件,直接将curl的输出通过管道传给jq就能生成符合要求的结果:

1. 生成CSV格式输出

curl <你的API请求地址> | jq -r '
  # 输出CSV表头
  ["id", "name", "address"],
  # 遍历data数组中的每个条目
  .data[] | [
    .id,
    .name,
    # 按规则处理address列
    if ._embedded.addresses | type == "array" then
      if length > 0 then ._embedded.addresses[0].ip else "[]" end
    elif ._embedded.addresses | type == "object" then
      if keys | length == 0 then "{}" else (._embedded.addresses.ip // "{}") end
    else
      ""
    end
  ] | @csv
'

2. 生成格式化表格输出(非CSV)

如果需要更易读的对齐表格,可结合column命令:

curl <你的API请求地址> | jq -r '
  ["ID", "NAME", "ADDRESS"],
  .data[] | [
    .id,
    .name,
    if ._embedded.addresses | type == "array" then
      if length > 0 then ._embedded.addresses[0].ip else "[]" end
    elif ._embedded.addresses | type == "object" then
      if keys | length == 0 then "{}" else (._embedded.addresses.ip // "{}") end
    else
      ""
    end
  ] | @tsv' | column -t -s $'\t'

命令说明

  • jq -r:输出原始字符串(避免额外的引号包裹)
  • 类型判断逻辑:
    • 若_embedded.addresses是非空数组,提取第一个元素的ip值
    • 若_embedded.addresses是空数组,输出[]
    • 若_embedded.addresses是空对象,输出{}
    • 若对象中存在ip字段则提取,否则仍输出{}
  • @csv/@tsv:将数组转为CSV/制表符分隔格式,自动处理特殊字符转义
  • column -t:将制表符分隔的内容对齐为美观的表格

内容的提问来源于stack exchange,提问作者Lazar Markovic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 01:10:57