4

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.

5

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
  • Thanks. What does "\($k)\n\(.[$k])" do? – Daniel Kaplan Jul 27 '18 at 19:44
  • NP. It prints the object key, a newline, and then the object itself. – Jesse_b Jul 27 '18 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.