How Do I Handle Newlines in Json?
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: Var Data = '{"Count": 1, "Stack"...
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:
var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');
This gives me an error:
unterminated string literal
With JSON.parse(data), I see similar error messages: "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.
10 Answers
This is what you want:
var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';
You need to escape the \ in your string (turning it into a double-\), otherwise it will become a newline in the JSON source, not the JSON data.
You will need to have a function which replaces \n to \\n in case data is not a string literal.
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));
Resulting dataObj will be
Object {count: 1, stack: "sometext\n\n"}
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.