Home > Software design >  Multiline JSON String notation
Multiline JSON String notation

Time:03-14

I know there are lots of questions on this topic already, but I somehow can find the right solution for my case.

So I want to outsource some user terms in a separate JSON file. As you can imagine those strings are pretty long.

{ 
      "term": "Terms and services", 
      "description": "*I´m a 300 words long string, which don´t want to stay in one line*" 
}

this would work, as long as it stays in one line- obviously. But I want this:

{
     
      "term": "Terms and services", 
      "description": "*first 30 words* 
                      *second thirty words* 
                      *third thirty words*
                      *...and so on*"
}

I already tried inserting backslashes or \n which also doesn´t work (I want the new lines to be displayed in the browser the same way they were written in the JSON document. Or are these long strings the absolute wrong usecase for JSON? What else could I use with the least effort?

Any ideas? Cheers!

CodePudding user response:

You're confusing the storage of data with the presentation of that data, these are separate concerns. JSON only deals with the storage of the data and as such doesn't support splitting a value out over multiple lines, for that your editor of choice should have a word-wrap option.

In terms of displaying the data with embedded line breaks, simply add whatever markup is used by the presentation layer to insert line-breaks, for example:

function addLinebreaks(str) {
    return str.replace(/\n/g, "<br>");
}

node.innerHTML = addLineBreaks(data.description);

Using something like this, any instance of \n in your source string is converted to a <br> tag in the rendered HTML.

CodePudding user response:

display newline on the web

You can achieve \n breaks with some simple css using the proper value for white-space. ( there are many other ways, but this seems the most appropriate approach based on the little data you gave ).

const div = document.getElementById('div');
const json = {
  some_text: "Hello \n there \n I should \n wrap \n lines"
}
div.textContent = json.some_text;
<div id='div' style="white-space: pre-line"></div>

Read more: https://www.w3.org/TR/CSS2/text.html#white-space-prop

in your code-editor

As far as I know you can't put multiline strings in a .json file.

You can however set your code editor to wrap overflowing text. Maybe there is even a plugin that makes a string wrap after /n appears in your code editor - I don't know, but it wouldn't surprise if that exists.

CodePudding user response:

You can't put multiple lines in JSON if possible you could use a javascript object instead:

const obj = {
    term: "Terms and services", 
    description: `*first 30 words* 
                      *second thirty words* 
                      *third thirty words*
                      *...and so on*`
}
  • Related