缘由
网上的在线json格式化有很多,但我是个有追求的人。在线的很难同时支持折叠、有缩进线、代码高亮、离线的,方便部署的、易用的、不请求后端(为了安全)的json格式化工具。
去Github上找项目,华而不实的东西占半个屏幕,格式化json要点好几下,一个json格式化工具npm安装之后几百个文件。或者npm报错跟本跑不起来。
三个字:没眼看。
于是自己写了一个。
展示
- Github地址:https://github.com/song1024/json-format-viewer
就一个html,把json粘贴进去之后自动格式化,且符合标题所有优质特点。
优雅之处
- 易用:这一个纯粹的格式化json的查看器工具,使用起来向弹出的文本框中添加要被转的json,点击确定,没有多余的操作。
- 方便部署:就一个html文件,原生JavaScript实现,不依赖任何库,可双击打开或者HTTP协议访问,部署在服务器上也非常方便。
- 代码高亮:彩色的文字用于美观,复制格式化后的结果,也能保证格式整齐。
- 支持折叠:方便查看层级关系,点击小三角可折叠或展开json,Ctrl + 点击,可递归到子级,支持。
- 支持缩进:更直观的展示层级关系,并有缩进线使其更加优雅。
- 离线的:没有依任何在线的库,网线断了也能用。
- 安全:这个项目放服务器上,它不访问任何接口或者资源,不会有RCE,SQL injection等漏洞。
- 可配置:如果您不喜欢文字的颜色、字体、或者其它配置,可任意修改。
代码
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON format viewer</title>
<style>
*{margin: 0; padding:0; font-size: 16px; font-family: "Consolas", "Arial", "Monaco", "Osaka", "serif"; background-color: #272822; color: #fff}
body {overflow-y: scroll; overflow-x: hidden;}
pre{white-space: pre-wrap; word-wrap: break-word; overflow-wrap: break-word; display: block;}
#json-renderer {padding: 1em 2em;}
ul.json-dict, ol.json-array {list-style-type: none; margin: 0 0 0 1px; border-left: 1px dotted #666; padding-left: 2em;}
.json-string-key {color: #7bdcfe;}
.json-string {color: #ce9178;}
.json-literal {color: #b5cea8; font-weight: bold;}
a.json-toggle {position: relative; color: inherit; text-decoration: none; cursor: pointer;}
a.json-toggle:focus {outline: none;}
a.json-toggle:before {font-size: 1.1em; color: #666; content: "\25BC"; position: absolute; display: inline-block; width: 1em; text-align: center; line-height: 1em; left: -1.2em;}
a.json-toggle:hover:before {color: #aaa;}
a.json-toggle.collapsed:before {content: "\25B6";}
a.json-placeholder {color: #aaa; padding: 0 1em; text-decoration: none; cursor: pointer;}
a.json-placeholder:hover {text-decoration: underline;}
.hidden {display: none;}
</style>
</head>
<body>
<pre id="json-renderer"></pre>
</body>
<script>
class JSONViewer {
constructor(options = {}) {
this.options = Object.assign({rootCollapsable: true, clickableUrls: true, bigNumbers: false}, options);
}
isCollapsable(arg) {
return arg instanceof Object && Object.keys(arg).length > 0;
}
isUrl(string) {
const protocols = ['http', 'https', 'ftp', 'ftps'];
return protocols.some(protocol => string.startsWith(protocol + '://'));
}
htmlEscape(s) {return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/"/g, '"');}
json2html(json) {
let html = '';
if (typeof json === 'string') {
json = this.htmlEscape(json);
if (this.options.clickableUrls && this.isUrl(json)) {
html += `<a href="${json}" class="json-string" target="_blank">${json}</a>`;
} else {
json = json.replace(/"/g, '\\"');
html += `<span class="json-string">"${json}"</span>`;
}
} else if (typeof json === 'number' || typeof json === 'bigint') {
html += `<span class="json-literal">${json}</span>`;
} else if (typeof json === 'boolean') {
html += `<span class="json-literal">${json}</span>`;
} else if (json === null) {
html += '<span class="json-literal">null</span>';
} else if (Array.isArray(json)) {
if (json.length > 0) {
html += '[<ol class="json-array">';
for (let i = 0; i < json.length; ++i) {
html += '<li>';
if (this.isCollapsable(json[i])) {
html += '<a class="json-toggle"></a>';
}
html += this.json2html(json[i]);
if (i < json.length - 1) {
html += ',';
}
html += '</li>';
}
html += '</ol>]';
} else {
html += '[]';
}
} else if (typeof json === 'object') {
if (this.options.bigNumbers && (typeof json.toExponential === 'function' || json.isLosslessNumber)) {
html += `<span class="json-literal">${json.toString()}</span>`;
} else {
const keyCount = Object.keys(json).length;
if (keyCount > 0) {
html += '{<ul class="json-dict">';
let count = 0;
for (const key in json) {
if (Object.prototype.hasOwnProperty.call(json, key)) {
const jsonElement = json[key];
const escapedKey = this.htmlEscape(key);
const keyRepr = `<span class="json-string-key">"${escapedKey}"</span>`;
html += '<li>';
if (this.isCollapsable(jsonElement)) {
html += `<a class="json-toggle">${keyRepr}</a>`;
} else {
html += keyRepr;
}
html += ': ' + this.json2html(jsonElement);
if (++count < keyCount) {
html += ',';
}
html += '</li>';
}
}
html += '</ul>}';
} else {
html += '{}';
}
}
}
return html;
}
render(jsonData) {
const html = this.json2html(jsonData);
const rootElement = document.getElementById('json-renderer');
if (this.options.rootCollapsable && this.isCollapsable(jsonData)) {
rootElement.innerHTML = '<a class="json-toggle"></a>' + html;
} else {
rootElement.innerHTML = html;
}
const toggleChildren = (element, collapse) => {
const childToggles = element.querySelectorAll('.json-toggle');
childToggles.forEach(toggle => {
const container = toggle.nextElementSibling;
if (container && (container.classList.contains('json-dict') || container.classList.contains('json-array'))) {
const isCollapsed = toggle.classList.contains('collapsed');
if (collapse !== isCollapsed) {
toggle.click();
}
}
});
};
document.addEventListener('click', (e) => {
if (e.target.matches('.json-toggle')) {
e.preventDefault();
const target = e.target;
const listItem = target.closest('li') || target.parentElement;
target.classList.toggle('collapsed');
const container = target.nextElementSibling;
if (container && (container.classList.contains('json-dict') || container.classList.contains('json-array'))) {
container.classList.toggle('hidden');
if (e.ctrlKey) {
toggleChildren(container, target.classList.contains('collapsed'));
}
const siblings = container.parentNode.children;
for (let i = Array.from(siblings).indexOf(container) + 1; i < siblings.length; i++) {
if (siblings[i].classList.contains('json-placeholder')) {
siblings[i].remove();
i--;
}
}
if (container.classList.contains('hidden')) {
const count = container.children.length;
let placeholder = document.createElement('a');
placeholder.className = 'json-placeholder';
placeholder.textContent = `${count} ${count > 1 ? 'items' : 'item'}`;
if (!container.nextElementSibling?.classList.contains('json-placeholder')) {
container.parentNode.insertBefore(placeholder, container.nextSibling);
}
}
}
} else if (e.target.matches('.json-placeholder')) {
e.preventDefault();
const toggle = e.target.previousElementSibling.previousElementSibling;
if (toggle) {
toggle.click();
}
}
});
}
}
const inputJson = prompt('Please enter json in the text box below:', '');
if (! inputJson) {
document.write('Empty json data.');
} else {
try {
const viewer = new JSONViewer({clickableUrls: false});
viewer.render(JSON.parse(inputJson));
} catch (error) {
document.write('Wrong json format.');
}
}
</script>
</html>
标签:container,代码,离线,toggle,else,json,html,const
From: https://www.cnblogs.com/phpphp/p/18660423