Linux: sed to cleanup json that has errant text surrounding it

If you have to ssh to a remote system to produce a block of json, it may be preceded and suffixed with login and system messages.  Or you may have a program that sends json as the main part of its output, but also sends debug type messages to stdout that need to be cleaned.

Here is how you can have sed remove all characters until it sees the opening bracket “{“, and then removes all text from the end until it reaches the closing bracket “}”

<processThatReturnsSingleLine> | sed 's/^[^{]*//g' | sed 's/[^}]*$//g'

If the output is multi-line, then you need to use the common pattern to process blocks of text as paragraphs, and it would look like this:

cat junk.json | sed '/./{H;$!d} ; x ; s/^[^{]*//g' | sed '/./{H;$!d} ; x ; s/[^}]*$//g'

REFERENCE

Multi-line handling in sed