【问题标题】:How to display breaks in pre tag via formatted json?如何通过格式化的 json 在 pre 标签中显示中断?
【发布时间】:2014-04-19 03:13:50
【问题描述】:

我有一些想要在网页中显示的 json。但是,pre 标记正在剥离并尊重输出中的中断?

如何显示一些 json 并保持所有文本不变?

注意:我无法控制语法。这就是我的服务中的内容,所以我只是将其以 html 形式注入到 pre 中。

<div>
    <pre>
        {
        "text:" "testing line breaks<br/>new line"
        }
    </pre>
</div>

输出:

{
 "text:" "testing line breaks
new line"
}

预期输出:

{
 "text:" "testing line breaks<br/>new line"
}

【问题讨论】:

标签: html css json


【解决方案1】:

您基本上需要做的是转义 HTML。您可以使用您正在使用的任何语言来输出字符串,但这里有一个使用本机 JavaScript 和 jQuery 的示例:

var data = { data: 'This is not a <br /> new line' }
// Doesn't escape HTML
$('#1').html(JSON.stringify(data) );
// Escapes
$('#2').text(JSON.stringify(data) );
// Escapes
document.getElementById("3").innerText = JSON.stringify(data);
// Doesn't escape
document.getElementById("4").innerHTML = JSON.stringify(data);
// Escapes
document.getElementById("5").innerHTML = JSON.stringify(data).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');

注意:如果您无法访问此 HTML 的生成方式,您仍然可以使用一点 Javascript sn-p 来修复它:

// If you can't decode the HTML but you can add a little snippet
var el = document.getElementById("6"); el.innerText = el.innerHTML;

// Using jQuery
var $el = $('#7'); $el.text( $el.html() ); 

jsFiddle

【讨论】:

    【解决方案2】:

    看看这个FIDDLE

    var data = {
      "text": "testing line breaks<br/>new line"
    };
    
    document.getElementsByTagName("pre")[0].innerText = JSON.stringify(data, null, 2);
    

    这里有两件重要的事情。

    1. element.innerText 将不支持 HTML br 标签
    2. JSON.stringify 的第三个参数在漂亮打印时需要使用多个空格

    【讨论】:

      【解决方案3】:

      开始使用jsonlint

      问题是 json 应该是这样的语法

          { "text": "testing line breaks<br\/>new line" }
      

      【讨论】:

      • 我无法控制语法。这就是我的服务。
      【解决方案4】:

      只需将“&lt;

      <div>
          <pre>
              {
              "text": "testing line breaks &lt;br/> new line"
              }
          </pre>
      </div>
      

      JSFIDDLE DEMO

      【讨论】:

      • 结束引号需要在冒号之前
      猜你喜欢
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      相关资源
      最近更新 更多