TLDR: A solution to the author's problem.
Use String.raw literal:
var data = String.raw`{"count" : 1, "stack" : "sometext\n\n"}`;
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.
Strictly based on the question title :
How do I handle newlines in JSON?
Let's say you parse a JSON file using the following code in node (it could be any language though):
let obj = JSON.parse(fs.readFileSync('file.json'));
console.log(obj.mykey)
Below is the output for each of the possible contents of file.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
Conclusion 1:
To represent a newline inside a json file we should use the \n character. To represent the \n we should use \\n.
How would we define each of the above inputs using JavaScript (instead of input file):
When we need to define a string containing JSON in JavaScript, things change a bit because of the special meaning that \n has also for JavaScript. But also notice how String.raw literal fixes this.
Input1:
let input1 = '{"mykey": "my multiline\nvalue"}'
//OR
let input1 = `{
"mykey": "my multiline
value"
}`;
//(or even)
let input1 = `{
"mykey": "my multiline\nvalue"
}`;
//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
Conclusion 2:
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 easiest way to create json in javascript, in general, is to convert a javascript object to json (using JSON.stringify).