user9371654
user9371654

Reputation: 2398

Adding comma between objects in json file

I have a large json table and I need to add comm between json objects on it. I can not do this manually. The file structure looks like:

[{"host"
}
{"host"
}
{"host"
}
]

I need to modify it using sed to be like:

[{"host"
},
{"host"
},
{"host"
}
]

I executed the following command. I did not get any error. But nothing changed in the file:

sed -i 's/}{"host"/},{"host"/g' result.json 

I suspect that I should consider that }{ are separated by new line? I tried to add \n in the command but also did not work.

Upvotes: 1

Views: 907

Answers (2)

Michael Dyck
Michael Dyck

Reputation: 2458

Instead of trying to insert the comma before the newline, you could easily insert it after:

sed 's/^{"host"/,&/'

The result looks a bit odd, but a conformant JSON-reader shouldn't care.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204164

With GNU awk for multi-char RS:

$ awk -v RS='^$' -v ORS= '{gsub(/}\n{/,"},\n{")}1' file
[{"host"
},
{"host"
},
{"host"
}
]

or if you prefer:

$ awk -v RS='}\n{' '{ORS=(RT ? "},\n{" : "")} 1' file
[{"host"
},
{"host"
},
{"host"
}
]

or with GNU sed for -z and to recognize \n as a newline:

$ sed -z 's/}\n{/},\n{/g' file
[{"host"
},
{"host"
},
{"host"
}
]

Upvotes: 1

Related Questions