当解析为JSON字符串对象时,换行符不起作用

问题描述:

我在解析该标题时遇到了一些麻烦,但是我的问题是当我解析为html时,我的JSON字典中的字符串中的\ n字符被取消。当解析为JSON字符串对象时,换行符不起作用

var exp = { 
 
"globalRunInfo" : { 
 
\t \t "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" 
 
\t } 
 
} 
 

 
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>

有谁知道如何解决这一问题?我试图避免编写一个检查换行符的函数,并用断点或其他东西替换它们。对于我将要使用一次的东西来说,这是很多工作。

尝试在span元素上设置CSS属性white-space: pre-wrap。这将导致新的行字符的制动。

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

您可以将类分配到区域,使用white-space: pre-wrap

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. 

此外,您也可以后\n这样就不会删除多余的空间获得添加到新行前面的空间。

var exp = { 
 
"globalRunInfo" : { 
 
\t \t "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" 
 
\t } 
 
} 
 

 
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>