Split a JSON array into multiple files

filesjqjson

I have a file that looks like this:

[
  {
    "billingAccountNumber": "x",
    "paymentResponseObject": {
      "uiErrorDipslayMessage": "",
      "transactionStatus": "S",
      "transactionDescription": "",
      "transactionCode": "",
      "confirmationNumber": "1"
    }
  },
  {
    "billingAccountNumber": "y",
    "paymentResponseObject": {
      "uiErrorDipslayMessage": "",
      "transactionStatus": "S",
      "transactionDescription": "",
      "transactionCode": "",
      "confirmationNumber": "2"
    }
  },
  {
    "billingAccountNumber": "z",
    "paymentResponseObject": {
      "uiErrorDipslayMessage": "",
      "transactionStatus": "S",
      "transactionDescription": "",
      "transactionCode": "",
      "confirmationNumber": "3"
    }
  }
]

The data doesn't look exactly like this, and I have more than three elements. From this data, I want to create three files: x.json, y.json, and z.json. I want the contents of each of those files to be the contents of the paymentResponseObject.

Is there a way to do this with jq? I've figured out how to do this in awk, but it's very clunky and I want to be able to repeat this process with different schemas. I have to rewrite 80% of the awk script for each schema.

Best Answer

From this SO thread:

jq -cr 'keys[] as $k | "\($k)\n\(.[$k])"' input.json | while read -r key; do
  fname=$(jq --raw-output ".[$key].billingAccountNumber" input.json)
  read -r item
  printf '%s\n' "$item" > "./$fname"
done
Related Question