Handling text data including newlines in JSON

TiShow
Jul 13, 2023

This is a memo for exchanging text containing newlines in JSON.

A line break entered in a <textarea>, for example, is represented by \n.

JSON does not support \n, but replacing \n with <br> or escaping it like \n would work.

# When you want to output to HTML file
json.text.replace(/\n/g, '<br>')

# When you really want to output as "\n"
json.text.replace(/\n/g, '\\n')

# remove \n
json.text.replace(/\n/g, '')

/g is Regular expression.

You can exchange text data in a nice way.

--

--

TiShow

80% is the creation, the rest is depression. Developer and Data scientist. Looking for Physics Ph.D Twitter: @_t_i_show