Ale*_*xis 141 html javascript json pretty-print stringify
我JSON.stringify是一个json对象
result = JSON.stringify(message, my_json, 2)
Run Code Online (Sandbox Code Playgroud)
在2上面的说法应该是相当打印结果.如果我这样做,它会这样做alert(result).但是,我想通过将其附加到div中来将其输出给用户.当我这样做时,我只会出现一行.(我不认为它有效,因为中断和空格不被解释为html?)
{ "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 }
Run Code Online (Sandbox Code Playgroud)
有没有办法以JSON.stringify漂亮的打印方式将结果输出到div?
Dio*_*ode 366
请使用<pre> 标签
var data = {
"data": {
"x": "1",
"y": "1",
"url": "http://url.com"
},
"event": "start",
"show": 1,
"id": 50
}
document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);Run Code Online (Sandbox Code Playgroud)
<pre id="json"></pre>Run Code Online (Sandbox Code Playgroud)
我的建议基于:
var x = { "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 };
document.querySelector('#newquote').innerHTML = JSON.stringify(x, null, 6)
.replace(/\n( *)/g, function (match, p1) {
return '<br>' + ' '.repeat(p1.length);
});Run Code Online (Sandbox Code Playgroud)
<div id="newquote"></div>Run Code Online (Sandbox Code Playgroud)
如果您的<pre>标签显示单行 JSON,因为字符串已经是这样提供的(通过 api 或某些不受您控制的函数/页面),您可以像这样重新格式化它:
HTML:
<pre id="json">{"some":"JSON string"}</pre>
Run Code Online (Sandbox Code Playgroud)
JavaScript:
(function() {
var element = document.getElementById("json");
var obj = JSON.parse(element.innerText);
element.innerHTML = JSON.stringify(obj, undefined, 2);
})();
Run Code Online (Sandbox Code Playgroud)
或 jQuery:
$(formatJson);
function formatJson() {
var element = $("#json");
var obj = JSON.parse(element.text());
element.html(JSON.stringify(obj, undefined, 2));
}
Run Code Online (Sandbox Code Playgroud)
小智 7
用预标记包裹它
<pre> { JSON.stringify(todos, null, 4)}</pre>
Run Code Online (Sandbox Code Playgroud)
输出将是
[
{
"id": "6cbc8fc4-a89e-4afa-abc1-f72f27b14271",
"title": "shakil",
"completed": false
},
{
"id": "5ee68df8-e152-46ae-82e2-8eb49f477d6f",
"title": "kobir",
"completed": false
}
]
Run Code Online (Sandbox Code Playgroud)
全面披露我这个包的作者,但另一种方式来输出JSON或JavaScript对象以可读的方式完成能够跳过部分,其中倒塌等是nodedump,https://github.com/ragamufin/nodedump
小智 6
许多人对这些问题做出了非常奇怪的回答,这导致了不必要的工作量。
最简单的方法包括以下内容
在实际代码中,示例如下(将所有步骤组合在一起):
var input = document.getElementById("input").value;
document.getElementById("output").value = JSON.stringify(JSON.parse(input),undefined,2);
Run Code Online (Sandbox Code Playgroud)
output.value 将是您想要显示美化 JSON 的区域。
考虑您的 REST API 返回:
{"Intent":{"Command":"search","SubIntent":null}}
Run Code Online (Sandbox Code Playgroud)
然后您可以执行以下操作以漂亮的格式打印它:
<pre id="ciResponseText">Output will de displayed here.</pre>
var ciResponseText = document.getElementById('ciResponseText');
var obj = JSON.parse(http.response);
ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);
Run Code Online (Sandbox Code Playgroud)