Coder Perfect

In JSON, how do I handle newlines?

Problem

I’ve created some JSON and am attempting to convert it into a JavaScript object. I’m receiving errors all the time. Here’s what I’ve got:

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

This gives me an error:

unterminated string literal

Similar warning messages appear when using JSON.parse(data): “Unexpected token” in Chrome, and “unterminated string literal” in Firefox and IE.

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

Asked by polarbear

Solution #1

This is what you’re looking for:

var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';

Otherwise, it will become a newline in the JSON source, not the JSON data, unless you escape the in your string (converting it into a double-).

Answered by BlaM

Solution #2

If the data is not a string literal, you’ll need a function that replaces n with n.

function jsonEscape(str)  {
    return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
}

var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = JSON.parse(jsonEscape(data));

The dataObj that results will be

Object {count: 1, stack: "sometext\n\n"}

Answered by manish_s

Solution #3

In a nutshell, this is a solution to the author’s difficulty.

Use String.raw literal:

var data = String.raw`{"count" : 1, "stack" : "sometext\n\n"}`;

All of the answers in this section, for some reason, focus on how to parse a JSON string representation in JavaScript, which may lead to confusion over how to represent newlines in actual JSON. The latter is independent of language.

Based only on the title of the question:

Let’s imagine you want to parse a JSON file using the following code in node (or any other language):


let obj = JSON.parse(fs.readFileSync('file.json'));
console.log(obj.mykey)

The output for each of the file’s possible contents is shown below. json:

Input 1:

{
  "mykey": "my multiline
   value"
}

Output 1:

SyntaxError: Unexpected token

Input 2:

{
  "mykey": "my multiline\nvalue"
}

Output 2:

my multiline
value

Input 3:

{
  "mykey": "my multiline\\nvalue"
}

Output 3:

my multiline\nvalue

The n character should be used to denote a newline in a json file. We should use n to denote the n.

Because of the special significance that n has for JavaScript, things shift a little when we need to define a string containing JSON. But take note of how the String.raw literal corrects this.

Input1:

let input1 = '{"mykey": "my multiline\nvalue"}'

//OR
let input1 = `{
  "mykey": "my multiline
   value"
}`;

//OR
let input1 = String.raw`{
  "mykey": "my multiline
   value"
}`;

console.log(JSON.parse(input1).mykey);

//SyntaxError: Unexpected token
//in JSON at position [..]

Input 2:

let input2 = '{"mykey": "my multiline\\nvalue"}'

//OR
let input2 = `{
  "mykey": "my multiline\\nvalue"
}`;

//OR (Notice the difference from default literal)
let input2 = String.raw`{
  "mykey": "my multiline\nvalue"
}`;

console.log(JSON.parse(input2).mykey);

//my multiline
//value

Input 3:

let input3 = '{"mykey": "my multiline\\\\nvalue"}'

//OR
let input3 = `{
  "mykey": "my multiline\\\\nvalue"
}`;

//OR (Notice the difference from default literal)
let input3 = String.raw`{
  "mykey": "my multiline\\nvalue"
}`;

console.log(JSON.parse(input3).mykey);

//my multiline\nvalue

To define a json string in javascript the easiest way would be to use String.raw, because it does not require any escaping (Well apart from backtick which is escaped like this String.raw`abc${“`”}def` ).

Of course, the most straightforward technique to generate json in javascript is to transform a javascript object to json (using JSON.stringify).

Answered by Marinos An

Solution #4

http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf states in the specification:

As a result, you can’t directly pass 0x0A or 0x0C codes. It’s not allowed! For several well-defined codes from U+0000 to U+001F, the specification advises using escape sequences:

You should escape the escape syntax (double-escape – once for language/platform, once for JSON itself) because most computer languages utilize it for quoting:

jsonStr = "{ \"name\": \"Multi\\nline.\" }";

Answered by gavenkoa

Solution #5

You could just escape your string when uploading the value of the JSON field to the server and then unescape it when receiving the value in the client browser, for example.

The unescape command is available in all major browsers’ JavaScript implementations.

Example:

On the server:

response.write "{""field1"":""" & escape(RS_Temp("textField")) & """}"

In the browser:

document.getElementById("text1").value = unescape(jsonObject.field1)

Answered by Victor_Magalhaes

Post is based on https://stackoverflow.com/questions/42068/how-do-i-handle-newlines-in-json