How to use a line break in JSON?
When using JSON data from the backend to display text in HTML of your web application, we often encounter a problem where we need to change the paragraph or add a bullet point. To achieve the same, we sometimes settle by creating different object properties in the JSON for different paragraphs and bullets points. We display the same by using <br/> tag separated spans or paragraphs. This increases the complexity of the code and we end up with a messy code.
As we can’t add <br/> tag in JSON, we need to use \n (newline) before the start of the next paragraph or bullet point to break the line in JSON. You can now use a single object property for multiple paragraphs and bullet points. This significantly reduces the line of code in the HTML file.
Even after adding \n to the string, you still see that the JSON is not breaking into separate paragraphs. This is because the CSS property white-space is set to normal by default.
In order to break the line, one needs to add the following style to paragraph or span.
white-space: pre;
pre stands for preformatted text. It will preserve the white space and text will only wrap on line breaks.
Use case: When developing a FAQ page for your web application and the data is coming in form of JSON from the backend.