Search code examples
jsonexport-to-csvjq

Convert JSON Array to CSV


Trying to convert a JSON array into a CSV file using jq but not able to succeed. Following is my JSON output from curl command:

{
  "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
  }
}

I have tried using following referring to some solutions online but not working.

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

How should i modify the jq command to convert JSON to CSV ?


Solution

  • If you just want the results array of objects:

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