Denno Denno - 2 months ago 6
JSON Question

How to convert linefeed into literal "\n"

I'm having some trouble converting my file to a properly formatted json string.
Have been fiddling with

sed
for ages now, but it seems to mock me.
Am working on RHEL 6, if that matters.

I'm trying to convert this file (content):

Hi there...

foo=bar
tomàto=tomáto
url=http://www.stackoverflow.com


Into this json string:

{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl=http://www.stackoverflow.com"}


How would I replace the actual line feeds in the literal '\n' character?? This is where I'm utterly stuck!

I've been trying to convert line feeds into ";" first and then back to a literal "\n". Tried loops for each row in the file. Can't make it work...

Some help is much appreciated!
Thanks!

Answer

Use awk for this :

awk -v RS=^$ '{gsub(/\n/,"\\n");sub(/^/,"{\"text\":\"");sub(/\\n$/,"\"}")}1' file

Output

{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl=http://www.stackoverflow.com"}
Comments