javascript 带换行符的 HTML 中的 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16499804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:56:13  来源:igfitidea点击:

JSON in HTML with line breaks

javascripthtmljson

提问by Oskar Persson

I have some Javascript on my page that makes an ajax call which returns some JSON data.

我的页面上有一些 Javascript 可以进行 ajax 调用,返回一些 JSON 数据。

With the result I do this:

结果我这样做:

results = JSON.stringify(data, undefined, 2);
console.log(results);
$('.box').append(results);

.boxis just an empty div.

.box只是一个空的div。

console.log(results)gives me an indented result with linebreaks but the data in .boxis just all in one line.

console.log(results)给我一个带有换行符的缩进结果,但数据.box只是在一行中。

How can I make sure that the result in .boxis also on multiple lines and indented?

我怎样才能确保结果.box也在多行上并缩进?

回答by Darin Dimitrov

.box is just an empty div.

.box 只是一个空的 div。

Make it an empty <pre>instead:

<pre>改为空:

<pre class="box"></pre>

回答by Ian

I agree with using <pre>, but another optionis to replace all \nwith <br>elements, and spaces with &nbsp;. It's probably really unnecessary (since <pre>preserves the whitespace). You can try:

我同意使用<pre>,但另一种选择\n<br>元素替换 all ,用&nbsp;. 这可能真的没有必要(因为<pre>保留了空格)。你可以试试:

var data = {key1: "value1", key2: "value2", key3: {key4: "value4"}},
    results = JSON.stringify(data, undefined, 2),
    results2 = results.replace(/\n/g, "<br>").replace(/[ ]/g, "&nbsp;");
console.log(results);
$(".box").append(results2);

DEMO:http://jsfiddle.net/Yk5Pb/3/

演示:http : //jsfiddle.net/Yk5Pb/3/