Home > database >  Convert JSON file to have each set of curly brackets on a single line
Convert JSON file to have each set of curly brackets on a single line

Time:02-15

I have a simple JSON file like this:

{
  "user_id": 123,
  "value": 99
},
{
  "user_id": 122,
  "value": 100
}

but I need it to look like this:

{"user_id": 123, "value": 99}
{"user_id": 122, "value": 100}

Basically every set of curly brackets should be on its own line. I was hoping it would be simple with jq but I'm quite new to it. Thank you in advance.

CodePudding user response:

If you get rid of the comma between the two objects (which is definitely invalid JSON), then just use jq's --compact-output (or -c) option and the identity filter ..

jq --compact-output '.'
{"user_id":123,"value":99}
{"user_id":122,"value":100}

Demo

CodePudding user response:

jq can be used to wrap the input (as raw text) inside [...], with the result being parsable by its builtin fromjson filter. Split the resulting array into separate objects again, and use -c to output each object on a single line.

$ cat old.txt
{
  "user_id": 123,
  "value": 99
},
{
  "user_id": 122,
  "value": 100
} 
$ jq -csR '"[\(.)]" | fromjson |.[]' old.txt
{"user_id":123,"value":99}
{"user_id":122,"value":100}
  • Related