Home > OS >  Add string to each row when converting json to csv with JQ
Add string to each row when converting json to csv with JQ

Time:10-12

I'm trying to convert this JSON:

{
  "reservationSummary": {
    "pickLoc": {
      "locationCode": "EWR"
    }
  },
  "vehicleSummaryList": [
    {
      "carGroup": "Economy",
      "carClass": "A",
      "payNowRate": {
        "amount": "2327.49",
        "totalRateAmount": "3387.19"
      },
      "payLaterRate": {
        "amount": "2449.99",
        "totalRateAmount": "3540.79"
      }    },
    {
      "carGroup": "Compact",
      "carClass": "B",
      "payNowRate": {
        "amount": "2327.49",
        "totalRateAmount": "3387.19"
      },
      "payLaterRate": {
        "amount": "2449.99",
        "totalRateAmount": "3540.79"
      }    }
  ]
}

into a csv that looks like this:

EWR,A,Economy,A,3540.79
EWR,B,Compact,A,3540.79

NOTE: I added EWR (from .reservationSummary.pickLoc.locationCodeto the 1st column of each row.

I've successfully gotten the csv without it like this:

jq -r '(.vehicleSummaryList[] | [.carClass, .carGroup, .carAvailability, .payLaterRate.totalRateAmount])|@csv' examle.json

But any attempt to add .reservationSummary.pickLoc.locationCode like this:

jq -r '.reservationSummary.pickLoc.locationCode, (.vehicleSummaryList[] | [.carClass, .carGroup, .carAvailability, .payLaterRate.totalRateAmount])|@csv' examle.json

gets an error like this:

jq: error (at examle.json:51): string ("EWR") cannot be csv-formatted, only array

CodePudding user response:

@csv requires an array as input but .reservationSummary.pickLoc.locationCode only produces a string. Instead, make it an array by wrapping it into [] and then add the two arrays together using :

[.reservationSummary.pickLoc.locationCode]   (
  .vehicleSummaryList[]
  | [.carClass, .carGroup, .carAvailability, .payLaterRate.totalRateAmount]
)
| @csv
  • Related