【问题标题】:Convert JSON Array to CSV将 JSON 数组转换为 CSV
【发布时间】:2020-07-23 10:22:22
【问题描述】:

尝试使用 jq 将 JSON 数组转换为 CSV 文件,但未能成功。以下是 curl 命令的 JSON 输出:

{
  "requestID": "463aeb25-f4c3-40ba-a031-e62d698afc6e",
  "signature": {
    "id": "json",
    "ph_no": "json",
    "status": "json"
  },
  "results": [
    {
      "id": "9f34-66758813073c",
      "ph_no": "343434325",
      "status": "active"
    },
    {
      "id": "b1a2-30a14a68c576",
      "ph_no": "6767666764",
      "status": "active"
    },
    {
      "id": "9af4-5b231f05ce37",
      "ph_no": "546745435",
      "status": "active"
    },
    {
      "id": "99bd-ed67fd139074",
      "ph_no": "323246566",
      "status": "active"
    },
    {
      "id": "9ecc-8277c3ffa274",
      "ph_no": "6753643554",
      "status": "active"
    }
  ],
  "status": "success",
  "metrics": {
    "elapsedTime": "29.461027ms",
    "executionTime": "29.364961ms",
    "resultCount": 146,
    "resultSize": 13856
  }
}

我尝试使用以下参考一些在线解决方案但不起作用。

jq  -r '["id","ph_no","status"],(to_entries|.[]|[.key,.value.id,.value.ph_no,.value.status)|@csv'  temp.json

我应该如何修改jq 命令以将 JSON 转换为 CSV?

【问题讨论】:

  • 你想在 CSV 输出中得到什么?
  • 我需要结果中的值部分是逗号,分隔如下:9f34-66758813073c,343434325,active b1a2-30a14a68c576,6767666764,active

标签: json export-to-csv jq


【解决方案1】:

如果您只想要 results 对象数组:

jq -r '(["id","ph_no","status"], (.results[] | [.id, .ph_no, .status])) | @csv' temp.json

【讨论】:

  • 感谢您的回复,但我在控制台上看不到任何输出:/var/tmp/jq/jq -r '(["id","ph_no","status"], (.results [] | [.id, .ph_no, .status])) | @csv' test.json
  • @MayurKadam Works for me
  • 抱歉迟到了,但现在可以了。我的输入 json 有问题。再次感谢你:)
猜你喜欢
  • 2022-01-17
  • 1970-01-01
  • 2015-03-05
  • 2019-10-11
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
相关资源
最近更新 更多