Problem using paragraphs in JSON file

6

I'm creating a web application which uses JSON files to save site content.

In these files are saved small text fragments containing paragraphs. When I try to separate the paragraph using a \n\ or \n or \r\ or \r , I do not have the line break and if I use \n\ or \r\ the JSON file is not loaded.

What is the correct way to put line breaks to separate paragraphs into JSON files?

I've already tested HTML tags like <p> or <br/> but this would not work well for alerts.

JSON file:

{
  "pt":{
    "title":"Quem é Ohm Reaction",
    "article":"hadouken!\n asda"
    }
}
    
asked by LeandroLuk 12.12.2013 в 13:13

3 answers

4

Just a simple%% of the json's final string.

>>> var pessoa = { nome: 'James Bond', apresentacao: 'Meu nome é Bond...\n\nJames Bond.' };  
>>> console.log(pessoa.apresentacao);
Menu nome é Bond...

James Bond.
    
12.12.2013 / 13:23
6

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 regular expression literal (like Java) - or functions / constructors that create a regex from a string - need the double bars:

var regex1 = /(.)/;              // Regex: (.)
                                   // Valida "xx": sim
var regex2 = new RegExp("(.)");  // Regex: (.) 
                                   // Valida "xx": não
var regex3 = new RegExp("(.)\1"); // Regex: (.)
                                   // 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 that JSON was read from a file, no, because the backslash will be included directly in the string (and not interpreted anyway as an escape character).

I know this does not directly answer your question (since it was already determined in the comments that your problem was when displaying the text using HTML), but I hope it helps to illustrate why in some situations it uses \n and other \n : in the first you are "escaping" n , in the other you are escaping own \ (and keeping n intact).

    
13.12.2013 в 10:42
1

Assuming you are using quotation marks in your JSON file, use \n for line breaks.

The JSON format requires that certain special characters, such as line break, be "escaped" using \ . Therefore, to produce the string \n , you should escape the \ bar by using another bar before.

    
12.12.2013 в 13:14