Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How concatenate multiple json objects with a delimiter comma using jq

Tags:

json

bash

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! :)

like image 871
Eleanor Avatar asked Dec 02 '22 12:12

Eleanor


1 Answers

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'.

like image 152
peak Avatar answered Dec 21 '22 23:12

peak