Denno Denno - 1 year ago 90
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

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


Into this json string:

{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl="}

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!

Answer Source

Use awk for this :

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


{"text":"Hi there...\n\nfoo=bar\ntomàto=tomáto\nurl="}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download