-2

I recently found out about .json files and I am trying to put a multiline string inside a data value, but it is just simply not working. I've tried \n and \r and \n\r but none work when they get put into my div from jquery.

Am I missing something here? This is my json file:

{
    "lText": "space\nbreak",
}

And here is my javascript:

$.getJSON("/js/content.json", function (data) {
    $(".lander .title").text(data.lTitle);
    $(".lander .subtitle").text(data.lSubtitle);
    $(".lander .text").text(data.lText);
});
Sebastian Olsen
  • 10,318
  • 9
  • 46
  • 91

3 Answers3

4

Pre-emptive answer

div.innerHTML = s.split('\n').join('<br />');

but if you insist on jQuery

$.getJSON("/js/content.json", function (data) {
    $(".lander .title").text(data.lTitle);
    $(".lander .subtitle").text(data.lSubtitle);
    $(".lander .text").html(data.lText.split('\n').join('<br />'));
});
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • You can't use `.text()` to inject HTML content. You have to use `.html()`. – Pointy Jul 09 '15 at 02:26
  • @SebastianOlsen did you change that last line to use `.html()` as in the answer? If you use `.text()`, it won't work. – Pointy Jul 09 '15 at 02:27
  • I seem to have missed the '.html()' bit there, sorry. – Sebastian Olsen Jul 09 '15 at 02:29
  • FYI, if this is seriously what you were after, @SebastianOlsen, I've got 2 quick points. 1 - Just put the `
    ` in your JSON file to begin with. 2 - You are not trying to put a multiline string into a JSON file, you are trying to put HTML into a JSON file. Big difference - browsers will render HTML when added properly, but they will ignore whitespace for display. 3 - Make sure your usage of `
    ` as opposed to `
    ` is appropriate. The former is for XHTML where self-closing tags are allowed and required. It won't break something like HTML5 per se, but it's bad form and not 100% proper.
    – jimcavoli Jul 09 '15 at 02:39
  • @jimcavoli - have to disagree on your first point. Splitting on `\n` is trivial, and having the `raw` data could be useful for other purposes – Jaromanda X Jul 09 '15 at 02:41
0

You need to escape the "\" character for the newline like so:

{
    "lText": "space\\nbreak",
}

See https://stackoverflow.com/a/42073/1728884

Community
  • 1
  • 1
jimcavoli
  • 854
  • 9
  • 22
0

Try using this

$.getJSON("/js/content.json", function (data) {
    $(".lander .title").html(data.lTitle);
    $(".lander .subtitle").html(data.lSubtitle);
    $(".lander .text").html(data.lText);
});

And change \n to <br/>

Agung Santoso
  • 83
  • 1
  • 8