JSON.stringify 출력을 div에 예쁘게 인쇄
I JSON.stringify
물체 바이제이슨
result = JSON.stringify(message, my_json, 2)
2
위의 논거에서 결과를 꽤 출력해야 합니다. 요.alert(result)
div., div., div., div., div.에 추가해 하고 싶습니다이렇게 하면 한 줄밖에 표시되지 않습니다.(브레이크나 공백이 html로 해석되지 않기 때문에 동작하지 않는 것 같습니다.)
{ "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 }
JSON.stringify
브에에 ?쁜 ?? ????
★★★★★★★★★★★★★★★★★★★★★★★★를 사용해 주세요.<pre>
부착
데모 : 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>
이 JSON으로 합니다.<pre>
붙이다
의 '' ''가<pre>
태그는 JSON의 한 줄을 표시하는데, 이는 문자열이 이미 제공되는 방식이기 때문입니다(API 또는 제어 불가능한 일부 함수/페이지를 통해). 을 사용하다
HTML:
<pre id="json">{"some":"JSON string"}</pre>
JavaScript:
(function() {
var element = document.getElementById("json");
var obj = JSON.parse(element.innerText);
element.innerHTML = JSON.stringify(obj, undefined, 2);
})();
또는 jQuery:
$(formatJson);
function formatJson() {
var element = $("#json");
var obj = JSON.parse(element.text());
element.html(JSON.stringify(obj, undefined, 2));
}
제안의 근거는 다음과 같습니다.
- 각 '\n'(새 행)을 <br>로 바꿉니다.
- 각 공백을 &nsp;로 바꿉니다.
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>
한 공개는 이 입니다만, 쉬운 .nodedump
, https://github.com/ragamufin/nodedump
많은 사람들이 이러한 질문들에 대해 매우 이상한 반응을 만들어내서 필요 이상으로 많은 일을 하게 만든다.
이를 위한 가장 쉬운 방법은 다음과 같습니다.
- JSON.parse(값)를 사용한JSON 문자열 해석
- 해석된 문자열을 적절한 형식으로 Stringify - JSON.stringify(input, undefined, 2)
- 출력을 2단계의 값으로 설정합니다.
실제 코드의 예는 다음과 같습니다(모든 스텝을 조합).
var input = document.getElementById("input").value;
document.getElementById("output").value = JSON.stringify(JSON.parse(input),undefined,2);
output.value는 아름다운 JSON을 표시하는 영역입니다.
REST API 반환을 고려하십시오.
{"Intent":{"Command":"search","SubIntent":null}}
그런 다음 다음을 수행하여 적절한 형식으로 인쇄할 수 있습니다.
<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);
컴포넌트 상태를 JSX로 인쇄하다
render() {
return (
<div>
<h1>Adopt Me!</h1>
<pre>
<code>{JSON.stringify(this.state, null, 4)}</code>
</pre>
</div>
);
}
텍스트만 출력하는 것이 아니라 사용자를 위한 것이라면 https://github.com/padolsey/prettyprint.js과 같은 라이브러리를 사용하여 HTML 테이블로 출력할 수 있습니다.
white-space: pre
<pre>
않을 수 형식도 변경합니다.tag는 바람직하지 수 있습니다.
다음 저장소를 사용해 보십시오.https://github.com/amelki/json-pretty-html
, Html: Laravel, Codeigniter Html용입니다.<pre class="jsonPre"> </pre>
컨트롤러: 컨트롤러에서 다음과 같이 JSON 값을 반환합니다.
return json_encode($data, JSON_PRETTY_PRINT);
스크립트:<script> $('.jsonPre').html(result); </script>
결과는 다음과 같습니다.
React를 사용하는 경우 react-json-tree 패키지를 사용할 수도 있습니다.
데이터 소품을 수용하는 아래와 같은 컴포넌트를 만들었습니다.
import React from 'react';
import JSONTree from 'react-json-tree'
import './style.css';
const theme = {
scheme: 'monokai',
base00: '#272822',
base01: '#383830',
base02: '#49483e',
base03: '#75715e',
base04: '#a59f85',
base05: '#f8f8f2',
base06: '#f5f4f1',
base07: '#f9f8f5',
base08: '#f92672',
base09: '#fd971f',
base0A: '#f4bf75',
base0B: '#a6e22e',
base0C: '#a1efe4',
base0D: '#66d9ef',
base0E: '#ae81ff',
base0F: '#cc6633',
};
const TreeView = (props) => {
return (
<div className="tree-container">
<JSONTree
data={props.data}
theme={theme}
invertTheme={true}
hideRoot
labelRenderer={([key]) => {
return <strong>{key}:</strong>
}}
valueRenderer={(valueAsString, value) => {
return <span className="capitalize">{value}</span>;
}}
getItemString={() => ''}
/>
</div>
);
}
export default TreeView;
그리고 컴포넌트를 Import한 후 아래와 같은 html 요소 안에서 사용합니다.
<div>
<TreeView data={s.value} />
</div>
접을 수 있는 json을 표시하는 사용자는 renderjson을 사용할 수 있습니다.
다음은 렌더 js javascript를 html에 삽입한 예입니다.
<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
// Copyright © 2013-2014 David Caldwell <david@porkrind.org>
//
// 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": "ksm@pobox.com",
"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>
사전 태그로 포장합니다.
<pre> { JSON.stringify(todos, null, 4)}</pre>
그리고 출력은
[ { " id ] : "6cbc8fc4 - a89e - 4afa - fac1 - f72f27b14271", "facebil", "facebook" : "false }, {"id" : "5ee68df8 - efaceb8 - efac-46e-2-8eb49f477d6f", "f" : "f", "f", "f" : facebook", "f", "faceb" : false", "f", "f" : faceb", "f",
언급URL : https://stackoverflow.com/questions/16862627/json-stringify-output-to-div-in-pretty-print-way
'programing' 카테고리의 다른 글
JSON 정수: 크기 제한 (0) | 2023.02.11 |
---|---|
다른 어레이로 이동할 때 Vue Keep Alive 구성 요소 (0) | 2023.02.02 |
크로스 플랫폼 개발에는 .NET/Mono 또는 Java 중 어느 쪽을 선택하는 것이 좋을까요? (0) | 2023.02.02 |
두 날짜 간의 시간 차이를 분 단위로 계산 (0) | 2023.02.02 |
Java에서 toString()을 올바르게 덮어쓰려면 어떻게 해야 합니까? (0) | 2023.02.02 |