The use of double bars (\\n
, \\r
etc) is usually only necessary when dealing with a string representing another string:
var texto1 = "foo\nbar"; // foo
// bar
var texto2 = "'foo\nbar'"; // 'foo
// bar'
var texto3 = "'foo\\nbar'"; // 'foo\nbar'
This is the same reason why languages without a literal for regular expressions (like Java) - or functions/constructs that create a regex from a string - need double bars:
var regex1 = /(.)\1/; // Regex: (.)\1
// Valida "xx": sim
var regex2 = new RegExp("(.)\1"); // Regex: (.)
// Valida "xx": não
var regex3 = new RegExp("(.)\\1"); // Regex: (.)\1
// Valida "xx": sim
In the case of a JSON contained in a string, therefore, it is required:
var json1 = '{ "texto":"foo\nbar" }'; // { "texto":"foo
// bar" }
var json2 = '{ "texto":"foo\\nbar" }'; // { "texto":"foo\nbar" }
But if this JSON was read from a file, no, because the backslash will be included directly in the string (and not interpreted in any way as an escape character).
I know this does not directly answer your question (since it has already been determined in the comments that your problem was at the time of displaying text using HTML), but I hope it helps to illustrate why in some situations it is used \n
and others \\n
: in the first you are "escaping" the n
, in the other you are escaping own \
(and maintaining the n
intact).
This seems to be a problem of formatting the code when displaying it instead of a problem with the JSON format. How is the code you use to display it?
– utluiz
when I used it he brought the n as if it were part of the text, the n it really jumps to the next line... my mistake was that when I inserted the json in the div it showed the space but for the HTML n is represented as at most a space between characters... my solution will be to convert in the input
– LeandroLuk