Html JSON.stringify 以漂亮的打印方式输出到 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16862627/
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
JSON.stringify output to div in pretty print way
提问by Alexis
I JSON.stringify
a json object by
我JSON.stringify
是一个 json 对象
result = JSON.stringify(message, my_json, 2)
The 2
in the argument above is supposed to pretty print the result. It does this if i do something like alert(result)
. However, I want to output this to the user by appending it inside a div. When I do this I get just a single line showing up. (I don't think it is working because the breaks and spaces are not being interpreted as html?)
在2
上面的说法应该是相当打印结果。如果我做类似的事情,它会这样做alert(result)
。但是,我想通过将其附加到 div 中来将其输出给用户。当我这样做时,我只显示一行。(我认为它不起作用,因为中断和空格没有被解释为 html?)
{ "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 }
Is there a way to output the result of JSON.stringify
to a div in a pretty print way?
有没有办法以JSON.stringify
漂亮的打印方式将结果输出到 div?
回答by Diode
Please use a <pre>
tag
请使用<pre>
标签
demo : http://jsfiddle.net/K83cK/
演示:http: //jsfiddle.net/K83cK/
var data = {
"data": {
"x": "1",
"y": "1",
"url": "http://url.com"
},
"event": "start",
"show": 1,
"id": 50
}
document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>
回答by Adam
Make sure the JSON output is in a <pre>
tag.
确保 JSON 输出在<pre>
标签中。
回答by ragamufin
Full disclosure I am the author of this package but another way to output JSON or JavaScript objects in a readable way complete with being able skip parts, collapse them, etc. is nodedump
, https://github.com/ragamufin/nodedump
完全披露我是这个包的作者,但另一种以可读的方式输出 JSON 或 JavaScript 对象的方法是能够跳过部分,折叠它们等nodedump
,https://github.com/ragamufin/nodedump
回答by gaetanoM
My proposal is based on:
我的建议基于:
- replace each '\n' (newline) with a <br>
- replace each space with
- 用 <br> 替换每个 '\n'(换行符)
- 用 替换每个空格
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);
});
<div id="newquote"></div>
回答by thinkOfaNumber
If your <pre>
tag is showing a single-line of JSON because that's how the string is provided already (via an api or some function/page out of your control), you can reformat it like this:
如果您的<pre>
标签显示单行 JSON,因为字符串已经提供(通过 api 或某些不受您控制的函数/页面),您可以像这样重新格式化它:
HTML:
HTML:
<pre id="json">{"some":"JSON string"}</pre>
JavaScript:
JavaScript:
(function() {
var element = document.getElementById("json");
var obj = JSON.parse(element.innerText);
element.innerHTML = JSON.stringify(obj, undefined, 2);
})();
or jQuery:
或 jQuery:
$(formatJson);
function formatJson() {
var element = $("#json");
var obj = JSON.parse(element.text());
element.html(JSON.stringify(obj, undefined, 2));
}
回答by Siddarth Kanted
Consider your REST API returns:
考虑您的 REST API 返回:
{"Intent":{"Command":"search","SubIntent":null}}
Then you can do the following to print it in a nice format:
然后您可以执行以下操作以漂亮的格式打印它:
<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);
回答by Jason Livesay
If this is really for a user, better than just outputting text, you can use a library like this one https://github.com/padolsey/prettyprint.jsto output it as an HTML table.
如果这真的是为用户准备的,比仅仅输出文本更好,您可以使用这样的库https://github.com/padolsey/prettyprint.js将其输出为 HTML 表格。
回答by user7986267
use style white-space: pre
the <pre>
tag also modifies the text format which may be undesirable.
使用样式white-space: pre
的<pre>
标签也修改这可能是不可取的文本格式。
回答by kofifus
you can try this repository : https://github.com/amelki/json-pretty-html
你可以试试这个存储库:https: //github.com/amelki/json-pretty-html
回答by Bhanu Sharma
for those who want to show collapsible json can use renderjson
对于那些想要显示可折叠 json 的人可以使用renderjson
Here is the example by embedding the render js javascript in html
这是通过在 html 中嵌入渲染 js javascript 的示例
<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
// Copyright ? 2013-2014 David Caldwell <[email protected]>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
// Usage
// -----
// The module exports one entry point, the `renderjson()` function. It takes in
// the JSON you want to render as a single argument and returns an HTML
// element.
//
// Options
// -------
// renderjson.set_icons("+", "-")
// This Allows you to override the disclosure icons.
//
// renderjson.set_show_to_level(level)
// Pass the number of levels to expand when rendering. The default is 0, which
// starts with everything collapsed. As a special case, if level is the string
// "all" then it will start with everything expanded.
//
// renderjson.set_max_string_length(length)
// Strings will be truncated and made expandable if they are longer than
// `length`. As a special case, if `length` is the string "none" then
// there will be no truncation. The default is "none".
//
// renderjson.set_sort_objects(sort_bool)
// Sort objects by key (default: false)
//
// Theming
// -------
// The HTML output uses a number of classes so that you can theme it the way
// you'd like:
// .disclosure ("⊕", "?")
// .syntax (",", ":", "{", "}", "[", "]")
// .string (includes quotes)
// .number
// .boolean
// .key (object key)
// .keyword ("null", "undefined")
// .object.syntax ("{", "}")
// .array.syntax ("[", "]")
var module;
(module || {}).exports = renderjson = (function () {
var themetext = function (/* [class, text]+ */) {
var spans = [];
while (arguments.length)
spans.push(append(span(Array.prototype.shift.call(arguments)),
text(Array.prototype.shift.call(arguments))));
return spans;
};
var append = function (/* el, ... */) {
var el = Array.prototype.shift.call(arguments);
for (var a = 0; a < arguments.length; a++)
if (arguments[a].constructor == Array)
append.apply(this, [el].concat(arguments[a]));
else
el.appendChild(arguments[a]);
return el;
};
var prepend = function (el, child) {
el.insertBefore(child, el.firstChild);
return el;
}
var isempty = function (obj) {
for (var k in obj) if (obj.hasOwnProperty(k)) return false;
return true;
}
var text = function (txt) { return document.createTextNode(txt) };
var div = function () { return document.createElement("div") };
var span = function (classname) {
var s = document.createElement("span");
if (classname) s.className = classname;
return s;
};
var A = function A(txt, classname, callback) {
var a = document.createElement("a");
if (classname) a.className = classname;
a.appendChild(text(txt));
a.href = '#';
a.onclick = function () { callback(); return false; };
return a;
};
function _renderjson(json, indent, dont_indent, show_level, max_string, sort_objects) {
var my_indent = dont_indent ? "" : indent;
var disclosure = function (open, placeholder, close, type, builder) {
var content;
var empty = span(type);
var show = function () {
if (!content) append(empty.parentNode,
content = prepend(builder(),
A(renderjson.hide, "disclosure",
function () {
content.style.display = "none";
empty.style.display = "inline";
})));
content.style.display = "inline";
empty.style.display = "none";
};
append(empty,
A(renderjson.show, "disclosure", show),
themetext(type + " syntax", open),
A(placeholder, null, show),
themetext(type + " syntax", close));
var el = append(span(), text(my_indent.slice(0, -1)), empty);
if (show_level > 0)
show();
return el;
};
if (json === null) return themetext(null, my_indent, "keyword", "null");
if (json === void 0) return themetext(null, my_indent, "keyword", "undefined");
if (typeof (json) == "string" && json.length > max_string)
return disclosure('"', json.substr(0, max_string) + " ...", '"', "string", function () {
return append(span("string"), themetext(null, my_indent, "string", JSON.stringify(json)));
});
if (typeof (json) != "object") // Strings, numbers and bools
return themetext(null, my_indent, typeof (json), JSON.stringify(json));
if (json.constructor == Array) {
if (json.length == 0) return themetext(null, my_indent, "array syntax", "[]");
return disclosure("[", " ... ", "]", "array", function () {
var as = append(span("array"), themetext("array syntax", "[", null, "\n"));
for (var i = 0; i < json.length; i++)
append(as,
_renderjson(json[i], indent + " ", false, show_level - 1, max_string, sort_objects),
i != json.length - 1 ? themetext("syntax", ",") : [],
text("\n"));
append(as, themetext(null, indent, "array syntax", "]"));
return as;
});
}
// object
if (isempty(json))
return themetext(null, my_indent, "object syntax", "{}");
return disclosure("{", "...", "}", "object", function () {
var os = append(span("object"), themetext("object syntax", "{", null, "\n"));
for (var k in json) var last = k;
var keys = Object.keys(json);
if (sort_objects)
keys = keys.sort();
for (var i in keys) {
var k = keys[i];
append(os, themetext(null, indent + " ", "key", '"' + k + '"', "object syntax", ': '),
_renderjson(json[k], indent + " ", true, show_level - 1, max_string, sort_objects),
k != last ? themetext("syntax", ",") : [],
text("\n"));
}
append(os, themetext(null, indent, "object syntax", "}"));
return os;
});
}
var renderjson = function renderjson(json) {
var pre = append(document.createElement("pre"), _renderjson(json, "", false, renderjson.show_to_level, renderjson.max_string_length, renderjson.sort_objects));
pre.className = "renderjson";
return pre;
}
renderjson.set_icons = function (show, hide) {
renderjson.show = show;
renderjson.hide = hide;
return renderjson;
};
renderjson.set_show_to_level = function (level) {
renderjson.show_to_level = typeof level == "string" &&
level.toLowerCase() === "all" ? Number.MAX_VALUE
: level;
return renderjson;
};
renderjson.set_max_string_length = function (length) {
renderjson.max_string_length = typeof length == "string" &&
length.toLowerCase() === "none" ? Number.MAX_VALUE
: length;
return renderjson;
};
renderjson.set_sort_objects = function (sort_bool) {
renderjson.sort_objects = sort_bool;
return renderjson;
};
// Backwards compatiblity. Use set_show_to_level() for new code.
renderjson.set_show_by_default = function (show) {
renderjson.show_to_level = show ? Number.MAX_VALUE : 0;
return renderjson;
};
renderjson.set_icons('⊕', '?');
renderjson.set_show_by_default(false);
renderjson.set_sort_objects(false);
renderjson.set_max_string_length("none");
return renderjson;
})();
</script>
</head>
<body>
<div id="dest"></div>
</body>
<script type="application/javascript">
document.getElementById("dest").appendChild(
renderjson.set_show_by_default(true)
//.set_show_to_level(2)
//.set_sort_objects(true)
//.set_icons('+', '-')
.set_max_string_length(100)
([
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
},
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{ "value": "New", "onclick": "CreateNewDoc()" },
{ "value": "Open", "onclick": "OpenDoc()" },
{ "value": "Close", "onclick": "CloseDoc()" }
]
}
}
},
{
"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
},
{
"web-app": {
"servlet": [
{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "[email protected]",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
"templateProcessorClass": "org.cofax.WysiwygTemplate",
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
"templatePath": "templates",
"templateOverridePath": "",
"defaultListTemplate": "listTemplate.htm",
"defaultFileTemplate": "articleTemplate.htm",
"useJSP": false,
"jspListTemplate": "listTemplate.jsp",
"jspFileTemplate": "articleTemplate.jsp",
"cachePackageTagsTrack": 200,
"cachePackageTagsStore": 200,
"cachePackageTagsRefresh": 60,
"cacheTemplatesTrack": 100,
"cacheTemplatesStore": 50,
"cacheTemplatesRefresh": 15,
"cachePagesTrack": 200,
"cachePagesStore": 100,
"cachePagesRefresh": 10,
"cachePagesDirtyRead": 10,
"searchEngineListTemplate": "forSearchEnginesList.htm",
"searchEngineFileTemplate": "forSearchEngines.htm",
"searchEngineRobotsDb": "WEB-INF/robots.db",
"useDataStore": true,
"dataStoreClass": "org.cofax.SqlDataStore",
"redirectionClass": "org.cofax.SqlRedirection",
"dataStoreName": "cofax",
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
"dataStoreUser": "sa",
"dataStorePassword": "dataStoreTestQuery",
"dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
"dataStoreInitConns": 10,
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "debug",
"maxUrlLength": 500
}
},
{
"servlet-name": "cofaxEmail",
"servlet-class": "org.cofax.cds.EmailServlet",
"init-param": {
"mailHost": "mail1",
"mailHostOverride": "mail2"
}
},
{
"servlet-name": "cofaxAdmin",
"servlet-class": "org.cofax.cds.AdminServlet"
},
{
"servlet-name": "fileServlet",
"servlet-class": "org.cofax.cds.FileServlet"
},
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
"templatePath": "toolstemplates/",
"log": 1,
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
"logMaxSize": "",
"dataLog": 1,
"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
"dataLogMaxSize": "",
"removePageCache": "/content/admin/remove?cache=pages&id=",
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
"lookInContext": 1,
"adminGroupID": 4,
"betaServer": true
}
}],
"servlet-mapping": {
"cofaxCDS": "/",
"cofaxEmail": "/cofaxutil/aemail/*",
"cofaxAdmin": "/admin/*",
"fileServlet": "/static/*",
"cofaxTools": "/tools/*"
},
"taglib": {
"taglib-uri": "cofax.tld",
"taglib-location": "/WEB-INF/tlds/cofax.tld"
}
}
},
{
"menu": {
"header": "SVG Viewer",
"items": [
{ "id": "Open" },
{ "id": "OpenNew", "label": "Open New" },
null,
{ "id": "ZoomIn", "label": "Zoom In" },
{ "id": "ZoomOut", "label": "Zoom Out" },
{ "id": "OriginalView", "label": "Original View" },
null,
{ "id": "Quality" },
{ "id": "Pause" },
{ "id": "Mute" },
null,
{ "id": "Find", "label": "Find..." },
{ "id": "FindAgain", "label": "Find Again" },
{ "id": "Copy" },
{ "id": "CopyAgain", "label": "Copy Again" },
{ "id": "CopySVG", "label": "Copy SVG" },
{ "id": "ViewSVG", "label": "View SVG" },
{ "id": "ViewSource", "label": "View Source" },
{ "id": "SaveAs", "label": "Save As" },
null,
{ "id": "Help" },
{ "id": "About", "label": "About Adobe CVG Viewer..." }
]
}
},
{
"empty": {
"object": {},
"array": []
}
},
{
"really_long": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla posuere, orci quis laoreet luctus, nunc neque condimentum arcu, sed tristique sem erat non libero. Morbi et velit non justo rutrum pulvinar. Nam pellentesque laoreet lacus eget sollicitudin. Quisque maximus mattis nisl, eget tempor nisi pulvinar et. Nullam accumsan sapien sapien, non gravida turpis consectetur non. Etiam in vestibulum neque. Donec porta dui sit amet turpis efficitur laoreet. Duis eu convallis ex, vel volutpat lacus. Donec sit amet nunc a orci fermentum luctus."
}
]));
</script>
</html>