9

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

3

1 Answer 1

27

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

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, the OP appears to have invalid JSON objects in the input stream (trailing commas after the ItmId keys).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.