<p>I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:</p>

<pre><code>var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');
</code></pre>

<p>This gives me an error: </p>

<pre><code>unterminated string literal
</code></pre>

<p>With <code>JSON.parse(data)</code>, I see similar error messages: "<code>Unexpected token ↵</code>" in Chrome, and "<code>unterminated string literal</code>" in Firefox and IE.</p>

<p>When I take out the <code>\n</code> after <code>sometext</code> the error goes away in both cases. I can't seem to figure out why the <code>\n</code> makes <code>eval</code> and <code>JSON.parse</code> fail.  </p>

[{'answer_id': 42073, 'author': 'BlaM', 'author_id': 999, 'author_profile': 'https://Stackoverflow.com/users/999', 'pm_score': 10, 'selected': True, 'text': "<p>This is what you want:</p>\n<pre><code>var data = '{&quot;count&quot; : 1, &quot;stack&quot; : &quot;sometext\\\\n\\\\n&quot;}';\n</code></pre>\n<p>You need to escape the <code>\\</code> in your string (turning it into a double-<code>\\</code>), otherwise it will become a newline in the JSON source, not the JSON data.</p>\n"}, {'answer_id': 1111538, 'author': 'Ron', 'author_id': 2293628, 'author_profile': 'https://Stackoverflow.com/users/2293628', 'pm_score': 2, 'selected': False, 'text': '<p>You might want to look into this C# function to escape the string:</p>\n\n<p><a href="http://www.aspcode.net/C-encode-a-string-for-JSON-JavaScript.aspx" rel="nofollow noreferrer">http://www.aspcode.net/C-encode-a-string-for-JSON-JavaScript.aspx</a></p>\n\n<pre><code>public static string Enquote(string s)  \n{ \n    if (s == null || s.Length == 0)  \n    { \n        return "\\"\\""; \n    } \n    char         c; \n    int          i; \n    int          len = s.Length; \n    StringBuilder sb = new StringBuilder(len + 4); \n    string       t; \n\n    sb.Append(\'"\'); \n    for (i = 0; i &lt; len; i += 1)  \n    { \n        c = s[i]; \n        if ((c == \'\\\\\') || (c == \'"\') || (c == \'&gt;\')) \n        { \n            sb.Append(\'\\\\\'); \n            sb.Append(c); \n        } \n        else if (c == \'\\b\') \n            sb.Append("\\\\b"); \n        else if (c == \'\\t\') \n            sb.Append("\\\\t"); \n        else if (c == \'\\n\') \n            sb.Append("\\\\n"); \n        else if (c == \'\\f\') \n            sb.Append("\\\\f"); \n        else if (c == \'\\r\') \n            sb.Append("\\\\r"); \n        else \n        { \n            if (c &lt; \' \')  \n            { \n                //t = "000" + Integer.toHexString(c); \n                string t = new string(c,1); \n                t = "000" + int.Parse(tmp,System.Globalization.NumberStyles.HexNumber); \n                sb.Append("\\\\u" + t.Substring(t.Length - 4)); \n            }  \n            else  \n            { \n                sb.Append(c); \n            } \n        } \n    } \n    sb.Append(\'"\'); \n    return sb.ToString(); \n} \n</code></pre>\n'}, {'answer_id': 5191059, 'author': 'Manish Singh', 'author_id': 518493, 'author_profile': 'https://Stackoverflow.com/users/518493', 'pm_score': 6, 'selected': False, 'text': '<p>You will need to have a function which replaces <code>\\n</code> to <code>\\\\n</code> in case <code>data</code> is not a string literal.</p>\n\n<pre><code>function jsonEscape(str)  {\n    return str.replace(/\\n/g, "\\\\\\\\n").replace(/\\r/g, "\\\\\\\\r").replace(/\\t/g, "\\\\\\\\t");\n}\n\nvar data = \'{"count" : 1, "stack" : "sometext\\n\\n"}\';\nvar dataObj = JSON.parse(jsonEscape(data));\n</code></pre>\n\n<p>Resulting <code>dataObj</code> will be</p>\n\n<pre><code>Object {count: 1, stack: "sometext\\n\\n"}\n</code></pre>\n'}, {'answer_id': 6156153, 'author': 'GabrielP', 'author_id': 773563, 'author_profile': 'https://Stackoverflow.com/users/773563', 'pm_score': -1, 'selected': False, 'text': '<p>I encountered that problem while making a class in PHP&nbsp;4 to emulate json_encode (available in PHP&nbsp;5). Here\'s what I came up with:</p>\n\n<pre><code>class jsonResponse {\n    var $response;\n\n    function jsonResponse() {\n        $this-&gt;response = array(\'isOK\'=&gt;\'KO\', \'msg\'=&gt;\'Undefined\');\n    }\n\n    function set($isOK, $msg) {\n        $this-&gt;response[\'isOK\'] = ($isOK) ? \'OK\' : \'KO\';\n        $this-&gt;response[\'msg\'] = htmlentities($msg);\n    }\n\n    function setData($data=null) {\n        if(!is_null($data))\n            $this-&gt;response[\'data\'] = $data;\n        elseif(isset($this-&gt;response[\'data\']))\n            unset($this-&gt;response[\'data\']);\n    }\n\n    function send() {\n        header(\'Content-type: application/json\');\n        echo \'{"isOK":"\' . $this-&gt;response[\'isOK\'] . \'","msg":\' . $this-&gt;parseString($this-&gt;response[\'msg\']);\n        if(isset($this-&gt;response[\'data\']))\n            echo \',"data":\' . $this-&gt;parseData($this-&gt;response[\'data\']);\n        echo \'}\';\n    }\n\n    function parseData($data) {\n        if(is_array($data)) {\n            $parsed = array();\n            foreach ($data as $key=&gt;$value)\n                array_push($parsed, $this-&gt;parseString($key) . \':\' . $this-&gt;parseData($value));\n            return \'{\' . implode(\',\', $parsed) . \'}\';\n        }\n        else\n            return $this-&gt;parseString($data);\n    }\n\n    function parseString($string) {\n            $string = str_replace("\\\\", "\\\\\\\\", $string);\n            $string = str_replace(\'/\', "\\\\/", $string);\n            $string = str_replace(\'"\', "\\\\".\'"\', $string);\n            $string = str_replace("\\b", "\\\\b", $string);\n            $string = str_replace("\\t", "\\\\t", $string);\n            $string = str_replace("\\n", "\\\\n", $string);\n            $string = str_replace("\\f", "\\\\f", $string);\n            $string = str_replace("\\r", "\\\\r", $string);\n            $string = str_replace("\\u", "\\\\u", $string);\n            return \'"\'.$string.\'"\';\n    }\n}\n</code></pre>\n\n<p>I followed the rules mentioned <a href="http://www.json.org/fatfree.html" rel="nofollow noreferrer">here</a>. I only used what I needed, but I figure that you can adapt it to your needs in the language your are using. The problem in my case wasn\'t about newlines as I originally thought, but about the / not being escaped. I hope this prevent someone else from the little headache I had figuring out what I did wrong.</p>\n'}, {'answer_id': 13493212, 'author': 'ShivarajRH', 'author_id': 903527, 'author_profile': 'https://Stackoverflow.com/users/903527', 'pm_score': 0, 'selected': False, 'text': '<p>I used this function to strip newline or other characters in data to parse JSON data:</p>\n\n<pre><code>function normalize_str($str) {\n\n    $invalid = array(\n        \'Š\'=&gt;\'S\', \'š\'=&gt;\'s\',  \'Đ\'=&gt;\'Dj\', \'đ\'=&gt;\'dj\', \'Ž\'=&gt;\'Z\', \'ž\'=&gt;\'z\',\n        \'Č\'=&gt;\'C\', \'č\'=&gt;\'c\',  \'Ć\'=&gt;\'C\',  \'ć\'=&gt;\'c\',  \'À\'=&gt;\'A\', \'Á\'=&gt;\'A\', \'Â\'=&gt;\'A\', \'Ã\'=&gt;\'A\',\n        \'Ä\'=&gt;\'A\', \'Å\'=&gt;\'A\',  \'Æ\'=&gt;\'A\',  \'Ç\'=&gt;\'C\',  \'È\'=&gt;\'E\', \'É\'=&gt;\'E\', \'Ê\'=&gt;\'E\', \'Ë\'=&gt;\'E\',\n        \'Ì\'=&gt;\'I\', \'Í\'=&gt;\'I\',  \'Î\'=&gt;\'I\',  \'Ï\'=&gt;\'I\',  \'Ñ\'=&gt;\'N\', \'Ò\'=&gt;\'O\', \'Ó\'=&gt;\'O\', \'Ô\'=&gt;\'O\',\n        \'Õ\'=&gt;\'O\', \'Ö\'=&gt;\'O\',  \'Ø\'=&gt;\'O\',  \'Ù\'=&gt;\'U\',  \'Ú\'=&gt;\'U\', \'Û\'=&gt;\'U\', \'Ü\'=&gt;\'U\', \'Ý\'=&gt;\'Y\',\n        \'Þ\'=&gt;\'B\', \'ß\'=&gt;\'Ss\', \'à\'=&gt;\'a\',  \'á\'=&gt;\'a\',  \'â\'=&gt;\'a\', \'ã\'=&gt;\'a\', \'ä\'=&gt;\'a\', \'å\'=&gt;\'a\',\n        \'æ\'=&gt;\'a\', \'ç\'=&gt;\'c\',  \'è\'=&gt;\'e\',  \'é\'=&gt;\'e\',  \'ê\'=&gt;\'e\', \'ë\'=&gt;\'e\', \'ì\'=&gt;\'i\', \'í\'=&gt;\'i\',\n        \'î\'=&gt;\'i\', \'ï\'=&gt;\'i\',  \'ð\'=&gt;\'o\',  \'ñ\'=&gt;\'n\',  \'ò\'=&gt;\'o\', \'ó\'=&gt;\'o\', \'ô\'=&gt;\'o\', \'õ\'=&gt;\'o\',\n        \'ö\'=&gt;\'o\', \'ø\'=&gt;\'o\',  \'ù\'=&gt;\'u\',  \'ú\'=&gt;\'u\',  \'û\'=&gt;\'u\', \'ý\'=&gt;\'y\', \'ý\'=&gt;\'y\', \'þ\'=&gt;\'b\',\n        \'ÿ\'=&gt;\'y\', \'Ŕ\'=&gt;\'R\',  \'ŕ\'=&gt;\'r\',\n        "`" =&gt; "\'", "´" =&gt; "\'",  \'"\' =&gt; \',\',  \'`\' =&gt; "\'",\n        \'´\' =&gt; "\'", \'"\' =&gt; \'\\"\', \'"\' =&gt; "\\"", \'´\' =&gt; "\'",\n        "&amp;acirc;€™" =&gt; "\'",\n        "{" =&gt; "",\n        "~" =&gt; "",  "–" =&gt; "-",  "\'" =&gt; "\'",  "     " =&gt; " ");\n\n    $str = str_replace(array_keys($invalid), array_values($invalid), $str);\n\n    $remove = array("\\n", "\\r\\n", "\\r");\n    $str = str_replace($remove, "\\\\n", trim($str));\n\n    //$str = htmlentities($str, ENT_QUOTES);\n\n    return htmlspecialchars($str);\n}\n\necho normalize_str($lst[\'address\']);\n</code></pre>\n'}, {'answer_id': 16700486, 'author': 'Victor_Magalhaes', 'author_id': 751147, 'author_profile': 'https://Stackoverflow.com/users/751147', 'pm_score': 2, 'selected': False, 'text': '<p>You could just escape your string on the server when writing the value of the JSON field and unescape it when retrieving the value in the client browser, for instance.</p>\n\n<p>The JavaScript implementation of all major browsers have the unescape command.</p>\n\n<p>Example:</p>\n\n<p>On the server:</p>\n\n<pre><code>response.write "{""field1"":""" &amp; escape(RS_Temp("textField")) &amp; """}"\n</code></pre>\n\n<p>In the browser: </p>\n\n<pre><code>document.getElementById("text1").value = unescape(jsonObject.field1)\n</code></pre>\n'}, {'answer_id': 42899451, 'author': 'gavenkoa', 'author_id': 173149, 'author_profile': 'https://Stackoverflow.com/users/173149', 'pm_score': 4, 'selected': False, 'text': '<p>According to the specification, <a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf" rel="noreferrer">http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf</a>:</p>\n\n<blockquote>\n  <p>A string is a sequence of Unicode code points wrapped with quotation marks\n    (<code>U+0022</code>). All characters may be placed within the quotation marks except for the\n    characters that must be escaped: quotation mark (<code>U+0022</code>), reverse solidus\n    (<code>U+005C</code>), and the control characters <code>U+0000</code> to <code>U+001F</code>. There are two-character\n    escape sequence representations of some characters.</p>\n</blockquote>\n\n<p>So you can\'t pass <code>0x0A</code> or <code>0x0C</code> codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from <code>U+0000</code> to <code>U+001F</code>:</p>\n\n<ul>\n<li><code>\\f</code> represents the form feed character (<code>U+000C</code>).</li>\n<li><code>\\n</code> represents the line feed character (<code>U+000A</code>).</li>\n</ul>\n\n<p>As most of programming languages uses <code>\\</code> for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):</p>\n\n<pre><code>jsonStr = "{ \\"name\\": \\"Multi\\\\nline.\\" }";\n</code></pre>\n'}, {'answer_id': 55850752, 'author': 'Kamil Kiełczewski', 'author_id': 860099, 'author_profile': 'https://Stackoverflow.com/users/860099', 'pm_score': -1, 'selected': False, 'text': '<p>As I understand you question, it is not about parsing JSON because you can copy-paste your JSON into your code directly - so if this is the case then just copy your JSON direct to <code>dataObj</code> variable without wrapping it with single quotes  (tip: <code>eval==evil</code>) </p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>var dataObj = {"count" : 1, "stack" : "sometext\\n\\n"};\r\n\r\nconsole.log(dataObj);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 63137400, 'author': 'jerryurenaa', 'author_id': 11611288, 'author_profile': 'https://Stackoverflow.com/users/11611288', 'pm_score': 2, 'selected': False, 'text': "<p>well, it is not really necessary to create a function for this when it can be done simply with 1 CSS class.</p>\n<p>just wrap your text around this class and see the magic :D</p>\n<pre><code> &lt;p style={{whiteSpace: 'pre-line'}}&gt;my json text goes here \\n\\n&lt;/p&gt;\n</code></pre>\n<p>note: because you will always present your text in frontend with HTML you can add the style={{whiteSpace: 'pre-line'}} to any tag, not just the p tag.</p>\n"}, {'answer_id': 66531090, 'author': 'Marinos An', 'author_id': 1555615, 'author_profile': 'https://Stackoverflow.com/users/1555615', 'pm_score': 5, 'selected': False, 'text': '<p><strong>TLDR: A solution to the author\'s problem.</strong></p>\n<p><strong>Use <code>String.raw</code> literal:</strong></p>\n<pre class="lang-js prettyprint-override"><code>var data = String.raw`{&quot;count&quot; : 1, &quot;stack&quot; : &quot;sometext\\n\\n&quot;}`;\n</code></pre>\n<hr />\n<p>For some reason all answers inside here focus on how to parse a JSON string representation in JavaScript, which may cause confusion regarding how to represent newlines on actual JSON. The latter is not language-dependent.</p>\n<p><strong>Strictly based on the question title :</strong></p>\n<h2>How do I handle newlines in JSON?</h2>\n<p>Let\'s say you parse a JSON file using the following code in <code>node</code> (it could be any language though):</p>\n<pre class="lang-js prettyprint-override"><code>\nlet obj = JSON.parse(fs.readFileSync(\'file.json\'));\nconsole.log(obj.mykey)\n</code></pre>\n<p>Below is the output for each of the possible contents of <code>file.json</code>:</p>\n<p><strong>Input 1:</strong></p>\n<pre class="lang-json prettyprint-override"><code>{\n  &quot;mykey&quot;: &quot;my multiline\n   value&quot;\n}\n</code></pre>\n<p><strong>Output 1:</strong></p>\n<pre><code>SyntaxError: Unexpected token\n</code></pre>\n<p><strong>Input 2:</strong></p>\n<pre class="lang-json prettyprint-override"><code>{\n  &quot;mykey&quot;: &quot;my multiline\\nvalue&quot;\n}\n</code></pre>\n<p><strong>Output 2:</strong></p>\n<pre><code>my multiline\nvalue\n</code></pre>\n<p><strong>Input 3:</strong></p>\n<pre class="lang-json prettyprint-override"><code>{\n  &quot;mykey&quot;: &quot;my multiline\\\\nvalue&quot;\n}\n</code></pre>\n<p><strong>Output 3:</strong></p>\n<pre><code>my multiline\\nvalue\n</code></pre>\n<h3>Conclusion 1:</h3>\n<p><strong>To represent a newline inside a <code>json</code> file we should use the <code>\\n</code> character</strong>. To represent the <code>\\n</code> we should use <code>\\\\n</code>.</p>\n<hr />\n<h2>How would we define each of the above inputs using JavaScript (instead of input file):</h2>\n<p>When we need to define a string containing JSON in JavaScript, things change a bit because of the special meaning that <code>\\n</code> has also for JavaScript. <strong>But also notice how <code>String.raw</code> literal fixes this</strong>.</p>\n<p><strong>Input1:</strong></p>\n<pre class="lang-js prettyprint-override"><code>let input1 = \'{&quot;mykey&quot;: &quot;my multiline\\nvalue&quot;}\'\n\n//OR\nlet input1 = `{\n  &quot;mykey&quot;: &quot;my multiline\n   value&quot;\n}`;\n//(or even)\nlet input1 = `{\n  &quot;mykey&quot;: &quot;my multiline\\nvalue&quot;\n}`;\n\n//OR\nlet input1 = String.raw`{\n  &quot;mykey&quot;: &quot;my multiline\n   value&quot;\n}`;\n\nconsole.log(JSON.parse(input1).mykey);\n\n//SyntaxError: Unexpected token\n//in JSON at position [..]\n</code></pre>\n<p><strong>Input 2:</strong></p>\n<pre class="lang-js prettyprint-override"><code>let input2 = \'{&quot;mykey&quot;: &quot;my multiline\\\\nvalue&quot;}\'\n\n//OR\nlet input2 = `{\n  &quot;mykey&quot;: &quot;my multiline\\\\nvalue&quot;\n}`;\n\n//OR (Notice the difference from default literal)\nlet input2 = String.raw`{\n  &quot;mykey&quot;: &quot;my multiline\\nvalue&quot;\n}`;\n\nconsole.log(JSON.parse(input2).mykey);\n\n//my multiline\n//value\n\n</code></pre>\n<p><strong>Input 3</strong>:</p>\n<pre class="lang-js prettyprint-override"><code>let input3 = \'{&quot;mykey&quot;: &quot;my multiline\\\\\\\\nvalue&quot;}\'\n\n//OR\nlet input3 = `{\n  &quot;mykey&quot;: &quot;my multiline\\\\\\\\nvalue&quot;\n}`;\n\n//OR (Notice the difference from default literal)\nlet input3 = String.raw`{\n  &quot;mykey&quot;: &quot;my multiline\\\\nvalue&quot;\n}`;\n\nconsole.log(JSON.parse(input3).mykey);\n\n//my multiline\\nvalue\n</code></pre>\n<h3>Conclusion 2:</h3>\n<p>To define a <code>json</code> string in javascript the <strong>easiest way would be to use <code>String.raw</code></strong>, because it does not require any escaping (Well apart from backtick which is escaped like this <code>String.raw`abc${&quot;`&quot;}def` </code> ).</p>\n<p>Of course, the easiest way to create <code>json</code> in javascript, in general, is to convert a javascript object to json (using <code>JSON.stringify</code>).</p>\n'}]
['https://Stackoverflow.com/questions/42068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3636/']