简体   繁体   中英

newline character does not work when parsing as JSON string object

I was having some trouble phrasing that title, but my problem is that the \\n characters in strings in my JSON dictionary get nullified when I parse to html.

 var exp = { "globalRunInfo" : { "file" : "file/path/goes/here", "info" : "random junk here", "copyright" : "this is where I am getting my problem \\n the newline doesn't work \\n so all this gets formatted as one line" } } ko.applyBindings(exp);
 <!DOCTYPE html> <html> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <div data-bind="with: globalRunInfo"> <p data-bind="text: file"></p> <p>SOMETHING</p> <p data-bind="text: info"></p> <span data-bind="text: copyright"></span> </div> </html>

Does anyone know how to fix this? I'm trying to avoid writing a function that checks for newline characters and replaces them with breaks or something. It's a lot of work for something that I'm going to use once.

Try setting the CSS property white-space: pre-wrap on the span element. This will result in the braking of the new line character.

<span style="white-space: pre-wrap" data-bind="text: copyright"></span>

You can assign a class to the area and use white-space: pre-wrap

Taken from the white-space documentation :

pre-wrap
Sequences of whitespace are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

In addition you can also remove the extra space after \\n so you don't get the space added to the front of the new line.

 var exp = { "globalRunInfo" : { "file" : "file/path/goes/here", "info" : "random junk here", "copyright" : "this is where I am getting my problem \\nthe newline doesn't work \\nso all this gets formatted as one line" } } ko.applyBindings(exp);
 .example{ white-space: pre-wrap; }
 <!DOCTYPE html> <html> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <div data-bind="with: globalRunInfo"> <p data-bind="text: file"></p> <p>SOMETHING</p> <p data-bind="text: info"></p> <span class="example" data-bind="text: copyright"></span> </div> </html>

wrap the whole json text with pre tag. it worked with me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM