Eleanor
Eleanor

Reputation: 2847

How concatenate multiple json objects with a delimiter comma using jq

Here is my data:

{
  "ReferringUrl": "N",
  "OpenAccess": "0",
  "ItmId": "1694738780"
}
{
  "ReferringUrl": "L",
  "OpenAccess": "1",
  "ItmId": "1347809133"
}

I want it to be like this:

[
 {
  "ReferringUrl": "N",
  "OpenAccess": "0",
  "ItmId": "1694738780"
 },
 {
   "ReferringUrl": "L",
   "OpenAccess": "1",
   "ItmId": "1347809133"
 }
]

How to make it by using jq library? I use bash. Thank you! :)

Upvotes: 9

Views: 9755

Answers (1)

peak
peak

Reputation: 116690

Assuming the sequence of JSON objects is in a file named input.json, simply "slurp" it:

jq -s . input.json

If the objects are spread over multiple files, say input*.json, you can run: jq -s . input*.json.

Handling invalid JSON

If the "objects" are as originally shown (i.e., not strictly valid as JSON), then you could use a command-line tool such as any-json, json5, or hjson to convert them to JSON, one at a time. If there is more than one quasi-JSON object per file, then you might be able to use csplit or awk to split up the file.

Alternatively, if the objects follow the pattern established in the example, you could use GNU sed: sed -z 's/,\(\n}\)/\1/g'.

Upvotes: 27

Related Questions