IT-TOOLS-PRO v1 - 定制版开发者工具站
12个原创工具(批量条码/二维码识别/在线翻译/OCR/面单设计/AI修图/网站收藏/PDF工具/图片工具/文档转换等) + 卡密授权系统(CardAuth对接,30分钟试用,换卡/撤销) + 体验优化(中文默认/收藏/最近使用/菜单展开/宽屏/品牌页脚)
This commit is contained in:
commit
01ff133ac9
528 files changed
+50026
No files matched your search
@@ -0,0 +1,13 @@
|
||||
import { Braces } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
import { translate } from '@/plugins/i18n.plugin';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: translate('tools.json-prettify.title'),
|
||||
path: '/json-prettify',
|
||||
description: translate('tools.json-prettify.description'),
|
||||
keywords: ['json', 'viewer', 'prettify', 'format'],
|
||||
component: () => import('./json-viewer.vue'),
|
||||
icon: Braces,
|
||||
redirectFrom: ['/json-viewer'],
|
||||
});
|
||||
@@ -0,0 +1,927 @@
|
||||
<script setup lang="ts">
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import GenHistory from '@/tools/gen-history/GenHistory.vue';
|
||||
import { useGenHistory } from '@/tools/gen-history/gen-history';
|
||||
|
||||
const genHist = useGenHistory('json-prettify');
|
||||
|
||||
// ---------------- state ----------------
|
||||
const raw = useStorage('json-viewer:raw', '{"hello": "world", "list": [1, 2, 3], "nested": {"ok": true, "nothing": null}}');
|
||||
const indent = useStorage<string>('json-viewer:indent', '2'); // '2' | '4' | 'tab'
|
||||
const fontSize = useStorage<number>('json-viewer:font-size', 14);
|
||||
const view = ref<'tree' | 'code'>('tree');
|
||||
const unicodeOut = ref(false);
|
||||
const escapeOut = ref(false);
|
||||
const fullscreen = ref(false);
|
||||
const errorMsg = ref('');
|
||||
const toast = ref('');
|
||||
|
||||
const fileInput = ref<HTMLInputElement>();
|
||||
const textareaEl = ref<HTMLTextAreaElement>();
|
||||
const gutterEl = ref<HTMLElement>();
|
||||
|
||||
// ---------------- computed output ----------------
|
||||
function indentStr(): string {
|
||||
return indent.value === 'tab' ? '\t' : ' '.repeat(Number(indent.value) || 2);
|
||||
}
|
||||
|
||||
const parsed = computed<any | null>(() => {
|
||||
if (!raw.value.trim()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(raw.value);
|
||||
}
|
||||
catch (e: any) {
|
||||
return { __error: e?.message ?? '解析失败' };
|
||||
}
|
||||
});
|
||||
|
||||
const outputText = computed(() => {
|
||||
const p = parsed.value;
|
||||
if (p === null) {
|
||||
return '';
|
||||
}
|
||||
if ((p as any).__error) {
|
||||
return '';
|
||||
}
|
||||
let text = JSON.stringify(p, null, indentStr());
|
||||
if (unicodeOut.value) {
|
||||
text = text.replace(/[^\x00-\x7F]/g, ch => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
||||
}
|
||||
if (escapeOut.value) {
|
||||
text = text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\t/g, '\\t');
|
||||
}
|
||||
return text;
|
||||
});
|
||||
|
||||
watch(parsed, (p) => {
|
||||
errorMsg.value = p && (p as any).__error ? `JSON 解析失败:${(p as any).__error}` : '';
|
||||
});
|
||||
|
||||
// ---------------- lightweight JSON syntax highlight ----------------
|
||||
function escapeHtml(s: string): string {
|
||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
// single-pass tokenizer: strings (key when followed by colon) > literals > numbers
|
||||
const TOKEN_RE = /("(?:[^"\\]|\\.)*")(\s*:)?|\b(true|false|null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g;
|
||||
|
||||
const highlighted = computed(() => {
|
||||
if (view.value !== 'code' || !outputText.value) {
|
||||
return '';
|
||||
}
|
||||
const s = escapeHtml(outputText.value);
|
||||
return s.replace(TOKEN_RE, (m, str, colon, lit, num) => {
|
||||
if (str !== undefined) {
|
||||
return colon ? `<span class="h-key">${str}</span>${colon}` : `<span class="h-str">${str}</span>`;
|
||||
}
|
||||
if (lit !== undefined) {
|
||||
return `<span class="h-lit">${lit}</span>`;
|
||||
}
|
||||
return `<span class="h-num">${num}</span>`;
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------- line numbers ----------------
|
||||
const lineCount = computed(() => raw.value.split('\n').length);
|
||||
const lineNumbers = computed(() => Array.from({ length: lineCount.value }, (_, i) => i + 1));
|
||||
|
||||
function syncGutter() {
|
||||
if (gutterEl.value && textareaEl.value) {
|
||||
gutterEl.value.scrollTop = textareaEl.value.scrollTop;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- toolbar actions ----------------
|
||||
function flash(msg: string) {
|
||||
toast.value = msg;
|
||||
setTimeout(() => (toast.value = ''), 2000);
|
||||
}
|
||||
|
||||
function format() {
|
||||
const p = parsed.value;
|
||||
if (p === null) {
|
||||
raw.value = '';
|
||||
return;
|
||||
}
|
||||
if ((p as any).__error) {
|
||||
flash('JSON 格式有误,无法格式化');
|
||||
return;
|
||||
}
|
||||
raw.value = JSON.stringify(p, null, indentStr());
|
||||
}
|
||||
|
||||
function compress() {
|
||||
const p = parsed.value;
|
||||
if (!p || (p as any).__error) {
|
||||
flash('JSON 格式有误');
|
||||
return;
|
||||
}
|
||||
raw.value = JSON.stringify(p);
|
||||
}
|
||||
|
||||
function loadExample() {
|
||||
raw.value = JSON.stringify({
|
||||
name: 'IT-TOOLS-PRO',
|
||||
version: '1.0',
|
||||
active: true,
|
||||
author: null,
|
||||
tags: ['json', 'dev', 'tools'],
|
||||
config: { indent: 2, theme: 'light', nested: { deep: { value: 42, ratio: 3.14 } } },
|
||||
list: [{ id: 1, title: '第一条' }, { id: 2, title: '第二条' }],
|
||||
}, null, 2);
|
||||
}
|
||||
|
||||
function toggleUnicode() {
|
||||
unicodeOut.value = !unicodeOut.value;
|
||||
flash(unicodeOut.value ? '输出已转为 Unicode 转义' : '输出已还原');
|
||||
}
|
||||
|
||||
function toggleEscape() {
|
||||
escapeOut.value = !escapeOut.value;
|
||||
flash(escapeOut.value ? '输出已转义显示' : '输出已还原');
|
||||
}
|
||||
|
||||
function pickFile() {
|
||||
fileInput.value?.click();
|
||||
}
|
||||
|
||||
function onFile(e: Event) {
|
||||
const input = e.target as HTMLInputElement;
|
||||
const f = input.files?.[0];
|
||||
input.value = '';
|
||||
if (!f) {
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
raw.value = String(reader.result ?? '');
|
||||
flash(`已载入 ${f.name}`);
|
||||
};
|
||||
reader.readAsText(f);
|
||||
}
|
||||
|
||||
function download() {
|
||||
const blob = new Blob([outputText.value || raw.value], { type: 'application/json' });
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = 'data.json';
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
genHist.add({ title: '下载 JSON', detail: (outputText.value || raw.value).slice(0, 80) });
|
||||
}
|
||||
|
||||
async function copyOut() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(outputText.value);
|
||||
flash('已复制到剪贴板');
|
||||
genHist.add({ title: '复制输出', detail: outputText.value.slice(0, 80), dedupeTitle: true });
|
||||
}
|
||||
catch {
|
||||
flash('复制失败');
|
||||
}
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
raw.value = '';
|
||||
errorMsg.value = '';
|
||||
}
|
||||
|
||||
// ---------------- tree view ----------------
|
||||
interface Row {
|
||||
path: string;
|
||||
depth: number;
|
||||
label: string;
|
||||
type: 'object' | 'array' | 'string' | 'number' | 'boolean' | 'null';
|
||||
display: string;
|
||||
expandable: boolean;
|
||||
}
|
||||
|
||||
const expanded = ref(new Set<string>());
|
||||
const ROOT = '$';
|
||||
|
||||
function isContainer(v: any): v is Record<string, any> | any[] {
|
||||
return v !== null && typeof v === 'object';
|
||||
}
|
||||
|
||||
function allPaths(val: any, path: string, acc: string[] = []): string[] {
|
||||
if (!isContainer(val)) {
|
||||
return acc;
|
||||
}
|
||||
acc.push(path);
|
||||
const entries = Array.isArray(val) ? val.map((v, i) => [String(i), v]) : Object.entries(val);
|
||||
for (const [k, v] of entries) {
|
||||
allPaths(v, `${path}.${k}`, acc);
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
function buildRows(val: any, label: string, path: string, depth: number, rows: Row[]) {
|
||||
if (!isContainer(val)) {
|
||||
const type: Row['type'] = val === null ? 'null' : typeof val as Row['type'];
|
||||
rows.push({
|
||||
path,
|
||||
depth,
|
||||
label,
|
||||
type,
|
||||
display: type === 'string' ? `"${val}"` : String(val),
|
||||
expandable: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const isArray = Array.isArray(val);
|
||||
const entries: [string, any][] = isArray ? (val as any[]).map((v, i) => [String(i), v]) : Object.entries(val);
|
||||
rows.push({
|
||||
path,
|
||||
depth,
|
||||
label,
|
||||
type: isArray ? 'array' : 'object',
|
||||
display: isArray ? `[ ${entries.length} 项 ]` : `{ ${entries.length} 个键 }`,
|
||||
expandable: true,
|
||||
});
|
||||
if (!expanded.value.has(path)) {
|
||||
return;
|
||||
}
|
||||
for (const [k, v] of entries) {
|
||||
buildRows(v, isArray ? `[${k}]` : k, `${path}.${k}`, depth + 1, rows);
|
||||
}
|
||||
}
|
||||
|
||||
const treeRows = computed<Row[]>(() => {
|
||||
const p = parsed.value;
|
||||
if (!p || (p as any).__error) {
|
||||
return [];
|
||||
}
|
||||
const rows: Row[] = [];
|
||||
if (isContainer(p)) {
|
||||
buildRows(p, '$', ROOT, 0, rows);
|
||||
}
|
||||
else {
|
||||
rows.push({ path: ROOT, depth: 0, label: '$', type: typeof p as any, display: String(p), expandable: false });
|
||||
}
|
||||
return rows;
|
||||
});
|
||||
|
||||
function toggleNode(row: Row) {
|
||||
if (!row.expandable) {
|
||||
return;
|
||||
}
|
||||
const s = new Set(expanded.value);
|
||||
if (s.has(row.path)) {
|
||||
s.delete(row.path);
|
||||
}
|
||||
else {
|
||||
s.add(row.path);
|
||||
}
|
||||
expanded.value = s;
|
||||
}
|
||||
|
||||
function expandAll() {
|
||||
const p = parsed.value;
|
||||
if (!p || (p as any).__error) {
|
||||
return;
|
||||
}
|
||||
expanded.value = new Set(allPaths(p, ROOT));
|
||||
}
|
||||
|
||||
function collapseAll() {
|
||||
expanded.value = new Set([ROOT]);
|
||||
}
|
||||
|
||||
watch(parsed, (p) => {
|
||||
if (p && !p.__error) {
|
||||
expanded.value = new Set([ROOT]);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------- bottom converters ----------------
|
||||
function textTransform(fn: (s: string) => string, msg: string) {
|
||||
try {
|
||||
raw.value = fn(raw.value);
|
||||
flash(msg);
|
||||
genHist.add({ title: msg, detail: raw.value.slice(0, 80) });
|
||||
}
|
||||
catch (e: any) {
|
||||
flash(`转换失败:${e?.message ?? e}`);
|
||||
}
|
||||
}
|
||||
|
||||
const cnToUnicode = () => textTransform(s => s.replace(/[^\x00-\x7F]/g, ch => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`), '中文已转 Unicode');
|
||||
|
||||
const unicodeToCn = () => textTransform(s => s.replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))), 'Unicode 已转回中文');
|
||||
|
||||
const addEscape = () => textTransform(s => s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\t/g, '\\t'), '已添加转义');
|
||||
|
||||
const removeEscape = () => textTransform(s => s.replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\"/g, '"').replace(/\\\\/g, '\\'), '已去除转义');
|
||||
|
||||
function toGetParams() {
|
||||
const p = parsed.value;
|
||||
if (!p || (p as any).__error) {
|
||||
flash('请先输入合法 JSON');
|
||||
return;
|
||||
}
|
||||
const flat: Record<string, string> = {};
|
||||
const walk = (v: any, prefix: string) => {
|
||||
if (Array.isArray(v)) {
|
||||
v.forEach((item, i) => walk(item, `${prefix}[${i}]`));
|
||||
}
|
||||
else if (v !== null && typeof v === 'object') {
|
||||
Object.entries(v).forEach(([k, val]) => walk(val, prefix ? `${prefix}[${k}]` : k));
|
||||
}
|
||||
else {
|
||||
flat[prefix] = String(v);
|
||||
}
|
||||
};
|
||||
walk(p, '');
|
||||
raw.value = Object.entries(flat).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
|
||||
flash('已转为 GET 参数');
|
||||
genHist.add({ title: '转为 GET 参数', detail: raw.value.slice(0, 80) });
|
||||
}
|
||||
|
||||
function dictToJson() {
|
||||
textTransform((s) => {
|
||||
const t = s.trim();
|
||||
const fixed = t
|
||||
.replace(/'/g, '"')
|
||||
.replace(/\bTrue\b/g, 'true')
|
||||
.replace(/\bFalse\b/g, 'false')
|
||||
.replace(/\bNone\b/g, 'null')
|
||||
.replace(/,\s*([}\]])/g, '$1');
|
||||
return JSON.stringify(JSON.parse(fixed), null, indentStr());
|
||||
}, 'Dict 已转 JSON');
|
||||
}
|
||||
|
||||
function jsonToDict() {
|
||||
const p = parsed.value;
|
||||
if (!p || (p as any).__error) {
|
||||
flash('请先输入合法 JSON');
|
||||
return;
|
||||
}
|
||||
const repr = (v: any): string => {
|
||||
if (v === null) {
|
||||
return 'None';
|
||||
}
|
||||
if (typeof v === 'boolean') {
|
||||
return v ? 'True' : 'False';
|
||||
}
|
||||
if (typeof v === 'number') {
|
||||
return String(v);
|
||||
}
|
||||
if (typeof v === 'string') {
|
||||
return `'${v.replace(/'/g, "\\'")}'`;
|
||||
}
|
||||
if (Array.isArray(v)) {
|
||||
return `[${v.map(repr).join(', ')}]`;
|
||||
}
|
||||
return `{${Object.entries(v).map(([k, val]) => `'${k}': ${repr(val)}`).join(', ')}}`;
|
||||
};
|
||||
raw.value = repr(p);
|
||||
flash('JSON 已转 Dict');
|
||||
genHist.add({ title: 'JSON 已转 Dict', detail: raw.value.slice(0, 80) });
|
||||
}
|
||||
|
||||
// ---------------- code conversion (more menu) ----------------
|
||||
function jsonToXml() {
|
||||
const p = parsed.value;
|
||||
if (!p || (p as any).__error) {
|
||||
flash('请先输入合法 JSON');
|
||||
return;
|
||||
}
|
||||
const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const toXml = (v: any, tag: string): string => {
|
||||
if (v === null || v === undefined) {
|
||||
return `<${tag}/>`;
|
||||
}
|
||||
if (typeof v !== 'object') {
|
||||
return `<${tag}>${esc(String(v))}</${tag}>`;
|
||||
}
|
||||
const body = Array.isArray(v)
|
||||
? v.map(item => toXml(item, 'item')).join('')
|
||||
: Object.entries(v).map(([k, val]) => toXml(val, k)).join('');
|
||||
return `<${tag}>${body}</${tag}>`;
|
||||
};
|
||||
raw.value = '<?xml version="1.0" encoding="UTF-8"?>\n' + toXml(p, 'root');
|
||||
flash('已转为 XML');
|
||||
genHist.add({ title: 'JSON 转 XML', detail: raw.value.slice(0, 80) });
|
||||
}
|
||||
|
||||
function jsonToCsv() {
|
||||
const p = parsed.value;
|
||||
if (!Array.isArray(p) || !p.length || typeof p[0] !== 'object' || p[0] === null) {
|
||||
flash('CSV 转换需要「对象数组」格式的 JSON');
|
||||
return;
|
||||
}
|
||||
const cols = Array.from(new Set(p.flatMap(row => Object.keys(row))));
|
||||
const cell = (v: any) => {
|
||||
const s = v === null || v === undefined ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v);
|
||||
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
||||
};
|
||||
const lines = [cols.join(',')];
|
||||
for (const row of p) {
|
||||
lines.push(cols.map(c => cell((row as any)[c])).join(','));
|
||||
}
|
||||
raw.value = lines.join('\n');
|
||||
flash('已转为 CSV');
|
||||
genHist.add({ title: `JSON 转 CSV(${p.length} 行)`, detail: raw.value.slice(0, 80) });
|
||||
}
|
||||
|
||||
const moreOptions = [
|
||||
{ key: 'xml', label: 'JSON 转 XML' },
|
||||
{ key: 'csv', label: 'JSON 转 CSV(对象数组)' },
|
||||
];
|
||||
|
||||
function onMoreSelect(key: string) {
|
||||
if (key === 'xml') {
|
||||
jsonToXml();
|
||||
}
|
||||
else if (key === 'csv') {
|
||||
jsonToCsv();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- layout ----------------
|
||||
const rootEl = ref<HTMLElement>();
|
||||
const rootStyle = ref<Record<string, string>>({});
|
||||
|
||||
function fit() {
|
||||
if (fullscreen.value) {
|
||||
rootStyle.value = { position: 'fixed', inset: '0', zIndex: '9990', height: '100vh', flex: '1 1 100%', background: '#fff', padding: '12px 16px' };
|
||||
return;
|
||||
}
|
||||
const el = rootEl.value;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
const top = el.getBoundingClientRect().top;
|
||||
const height = Math.max(360, window.innerHeight - top - 12);
|
||||
rootStyle.value = { height: `${height}px`, flex: '1 1 100%' };
|
||||
}
|
||||
|
||||
watch(fullscreen, () => fit());
|
||||
|
||||
onMounted(() => {
|
||||
fit();
|
||||
window.addEventListener('resize', fit);
|
||||
expanded.value = new Set([ROOT]);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', fit);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="rootEl" class="jv-root" :style="rootStyle" :class="{ fullscreen }">
|
||||
<input ref="fileInput" type="file" accept=".json,application/json,.txt" style="display:none" @change="onFile">
|
||||
|
||||
<!-- ===== toolbar ===== -->
|
||||
<div class="jv-toolbar">
|
||||
<div class="jv-group">
|
||||
<c-button size="small" @click="format">
|
||||
</> 格式化
|
||||
</c-button>
|
||||
<c-button size="small" @click="compress">
|
||||
压缩
|
||||
</c-button>
|
||||
<c-button size="small" @click="loadExample">
|
||||
示例
|
||||
</c-button>
|
||||
<c-button size="small" :style="unicodeOut ? { borderColor: '#18a058', color: '#18a058' } : {}" @click="toggleUnicode">
|
||||
Unicode
|
||||
</c-button>
|
||||
<c-button size="small" :style="escapeOut ? { borderColor: '#18a058', color: '#18a058' } : {}" @click="toggleEscape">
|
||||
转义
|
||||
</c-button>
|
||||
<n-dropdown trigger="click" :options="moreOptions" @select="onMoreSelect">
|
||||
<c-button size="small">
|
||||
更多 ▾
|
||||
</c-button>
|
||||
</n-dropdown>
|
||||
|
||||
<span class="jv-sep" />
|
||||
<a href="javascript:;" class="jv-ico" title="上传 JSON 文件" @click="pickFile">上传</a>
|
||||
<a href="javascript:;" class="jv-ico" title="下载" @click="download">下载</a>
|
||||
<a href="javascript:;" class="jv-ico" title="复制输出" @click="copyOut">复制</a>
|
||||
<a href="javascript:;" class="jv-ico danger" title="清空" @click="clearAll">清空</a>
|
||||
</div>
|
||||
|
||||
<div class="jv-group">
|
||||
<button class="jv-viewbtn" :class="{ active: view === 'tree' }" @click="view = 'tree'">
|
||||
树视图
|
||||
</button>
|
||||
<button class="jv-viewbtn" :class="{ active: view === 'code' }" @click="view = 'code'">
|
||||
代码
|
||||
</button>
|
||||
<c-button size="small" :disabled="view !== 'tree'" @click="expandAll">
|
||||
全展开
|
||||
</c-button>
|
||||
<c-button size="small" :disabled="view !== 'tree'" @click="collapseAll">
|
||||
全折叠
|
||||
</c-button>
|
||||
</div>
|
||||
|
||||
<div class="jv-group right">
|
||||
<select v-model="indent" class="jv-select" title="缩进">
|
||||
<option value="2">
|
||||
2空格
|
||||
</option>
|
||||
<option value="4">
|
||||
4空格
|
||||
</option>
|
||||
<option value="tab">
|
||||
Tab
|
||||
</option>
|
||||
</select>
|
||||
<select v-model.number="fontSize" class="jv-select" title="字号">
|
||||
<option :value="12">
|
||||
12px
|
||||
</option>
|
||||
<option :value="14">
|
||||
14px
|
||||
</option>
|
||||
<option :value="16">
|
||||
16px
|
||||
</option>
|
||||
</select>
|
||||
<a href="javascript:;" class="jv-ico" :title="fullscreen ? '退出全屏' : '全屏'" @click="fullscreen = !fullscreen">
|
||||
{{ fullscreen ? '⤢ 退出' : '⛶ 全屏' }}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== body ===== -->
|
||||
<div class="jv-body">
|
||||
<!-- left: input -->
|
||||
<div class="jv-pane left">
|
||||
<div class="jv-editor" :style="{ fontSize: `${fontSize}px` }">
|
||||
<div ref="gutterEl" class="jv-gutter">
|
||||
<div v-for="n in lineNumbers" :key="n">
|
||||
{{ n }}
|
||||
</div>
|
||||
</div>
|
||||
<textarea
|
||||
ref="textareaEl"
|
||||
v-model="raw"
|
||||
class="jv-textarea"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
@scroll="syncGutter"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="jv-converters">
|
||||
<c-button size="tiny" @click="cnToUnicode">
|
||||
中文转Unicode
|
||||
</c-button>
|
||||
<c-button size="tiny" @click="unicodeToCn">
|
||||
Unicode转中文
|
||||
</c-button>
|
||||
<c-button size="tiny" @click="addEscape">
|
||||
添加转义
|
||||
</c-button>
|
||||
<c-button size="tiny" @click="removeEscape">
|
||||
去除转义
|
||||
</c-button>
|
||||
<c-button size="tiny" @click="toGetParams">
|
||||
转Get参数
|
||||
</c-button>
|
||||
<c-button size="tiny" @click="dictToJson">
|
||||
Dict转Json
|
||||
</c-button>
|
||||
<c-button size="tiny" @click="jsonToDict">
|
||||
Json转Dict
|
||||
</c-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- right: output -->
|
||||
<div class="jv-pane right">
|
||||
<div v-if="errorMsg" class="jv-error">
|
||||
{{ errorMsg }}
|
||||
</div>
|
||||
|
||||
<div v-else-if="!outputText" class="jv-placeholder">
|
||||
请在左侧输入JSON代码
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<pre v-if="view === 'code'" class="jv-code" :style="{ fontSize: `${fontSize}px` }" v-html="highlighted" />
|
||||
<div v-else class="jv-tree" :style="{ fontSize: `${fontSize}px` }">
|
||||
<div
|
||||
v-for="row in treeRows"
|
||||
:key="row.path"
|
||||
class="jv-node"
|
||||
:style="{ paddingLeft: `${10 + row.depth * 18}px` }"
|
||||
@click="toggleNode(row)"
|
||||
>
|
||||
<span class="jv-arrow" :class="{ open: expanded.has(row.path), leaf: !row.expandable }">{{ row.expandable ? '▸' : '' }}</span>
|
||||
<span class="jv-label">{{ row.label }}</span>
|
||||
<span class="jv-colon">:</span>
|
||||
<span class="jv-val" :class="`t-${row.type}`">{{ row.display }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="toast" class="jv-toast">
|
||||
{{ toast }}
|
||||
</div>
|
||||
|
||||
<GenHistory tool="json-prettify" position="right" label="操作记录" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.jv-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
box-sizing: border-box;
|
||||
background: #fff;
|
||||
border: 1px solid rgba(128, 128, 128, 0.2);
|
||||
border-radius: 12px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
// ---- toolbar ----
|
||||
.jv-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
flex-shrink: 0;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px solid rgba(128, 128, 128, 0.15);
|
||||
|
||||
.jv-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
|
||||
&.right {
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.jv-sep {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
background: rgba(128, 128, 128, 0.3);
|
||||
margin: 0 4px;
|
||||
}
|
||||
|
||||
.jv-ico {
|
||||
font-size: 12.5px;
|
||||
color: #666;
|
||||
text-decoration: none;
|
||||
padding: 2px 6px;
|
||||
border-radius: 5px;
|
||||
|
||||
&:hover {
|
||||
color: #18a058;
|
||||
background: rgba(24, 160, 88, 0.08);
|
||||
}
|
||||
|
||||
&.danger:hover {
|
||||
color: #d03050;
|
||||
background: rgba(208, 48, 80, 0.08);
|
||||
}
|
||||
}
|
||||
|
||||
.jv-viewbtn {
|
||||
border: 1px solid rgba(128, 128, 128, 0.35);
|
||||
background: transparent;
|
||||
border-radius: 6px;
|
||||
padding: 4px 14px;
|
||||
font-size: 12.5px;
|
||||
color: #666;
|
||||
cursor: pointer;
|
||||
|
||||
&.active {
|
||||
background: #2080f0;
|
||||
border-color: #2080f0;
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
|
||||
.jv-select {
|
||||
border: 1px solid rgba(128, 128, 128, 0.35);
|
||||
border-radius: 6px;
|
||||
padding: 3px 6px;
|
||||
font-size: 12px;
|
||||
color: #555;
|
||||
background: #fff;
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- body ----
|
||||
.jv-body {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@media (max-width: 860px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.jv-pane {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
&.left {
|
||||
border-right: 1px solid rgba(128, 128, 128, 0.18);
|
||||
|
||||
@media (max-width: 860px) {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid rgba(128, 128, 128, 0.18);
|
||||
}
|
||||
}
|
||||
|
||||
&.right {
|
||||
position: relative;
|
||||
}
|
||||
}
|
||||
|
||||
.jv-editor {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.jv-gutter {
|
||||
flex-shrink: 0;
|
||||
width: 40px;
|
||||
padding: 10px 6px 10px 0;
|
||||
text-align: right;
|
||||
font-family: monospace;
|
||||
color: rgba(128, 128, 128, 0.7);
|
||||
background: rgba(128, 128, 128, 0.05);
|
||||
user-select: none;
|
||||
overflow: hidden;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.jv-textarea {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
outline: none;
|
||||
resize: none;
|
||||
padding: 10px 12px;
|
||||
font-family: monospace;
|
||||
line-height: 1.5;
|
||||
background: transparent;
|
||||
color: #333;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.jv-converters {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
flex-shrink: 0;
|
||||
padding: 8px 4px 6px;
|
||||
border-top: 1px solid rgba(128, 128, 128, 0.15);
|
||||
}
|
||||
|
||||
.jv-placeholder {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0.4;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.jv-error {
|
||||
margin: 10px;
|
||||
padding: 10px 14px;
|
||||
background: rgba(208, 48, 80, 0.08);
|
||||
border: 1px solid rgba(208, 48, 80, 0.35);
|
||||
border-radius: 8px;
|
||||
color: #d03050;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.jv-code {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
margin: 0;
|
||||
padding: 10px 14px;
|
||||
overflow: auto;
|
||||
font-family: monospace;
|
||||
line-height: 1.55;
|
||||
color: #333;
|
||||
white-space: pre;
|
||||
|
||||
:deep(.h-key) {
|
||||
color: #881391;
|
||||
}
|
||||
|
||||
:deep(.h-str) {
|
||||
color: #1a7f37;
|
||||
}
|
||||
|
||||
:deep(.h-num) {
|
||||
color: #0550ae;
|
||||
}
|
||||
|
||||
:deep(.h-lit) {
|
||||
color: #cf222e;
|
||||
}
|
||||
}
|
||||
|
||||
.jv-tree {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: 8px 0;
|
||||
|
||||
.jv-node {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
line-height: 1.85;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
border-radius: 4px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(24, 160, 88, 0.06);
|
||||
}
|
||||
|
||||
.jv-arrow {
|
||||
width: 12px;
|
||||
flex-shrink: 0;
|
||||
color: #999;
|
||||
transition: transform 0.12s;
|
||||
display: inline-block;
|
||||
font-size: 11px;
|
||||
|
||||
&.open {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
&.leaf {
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
|
||||
.jv-label {
|
||||
color: #881391;
|
||||
}
|
||||
|
||||
.jv-colon {
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.jv-val {
|
||||
&.t-string {
|
||||
color: #1a7f37;
|
||||
}
|
||||
|
||||
&.t-number {
|
||||
color: #0550ae;
|
||||
}
|
||||
|
||||
&.t-boolean {
|
||||
color: #cf222e;
|
||||
}
|
||||
|
||||
&.t-null {
|
||||
color: #999;
|
||||
}
|
||||
|
||||
&.t-object,
|
||||
&.t-array {
|
||||
color: #666;
|
||||
font-size: 0.92em;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.jv-toast {
|
||||
position: fixed;
|
||||
right: 20px;
|
||||
bottom: 20px;
|
||||
background: rgba(30, 30, 30, 0.9);
|
||||
color: #fff;
|
||||
font-size: 13px;
|
||||
border-radius: 8px;
|
||||
padding: 9px 18px;
|
||||
z-index: 10000;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sortObjectKeys } from './json.models';
|
||||
|
||||
describe('json models', () => {
|
||||
describe('sortObjectKeys', () => {
|
||||
it('the object keys are recursively sorted alphabetically', () => {
|
||||
expect(JSON.stringify(sortObjectKeys({ b: 2, a: 1 }))).to.deep.equal(JSON.stringify({ a: 1, b: 2 }));
|
||||
// To unsure that this way of testing is working
|
||||
expect(JSON.stringify(sortObjectKeys({ b: 2, a: 1 }))).to.not.deep.equal(JSON.stringify({ b: 2, a: 1 }));
|
||||
|
||||
expect(JSON.stringify(sortObjectKeys({ b: 2, a: 1, d: { j: 7, a: [{ z: 9, y: 8 }] }, c: 3 }))).to.deep.equal(
|
||||
JSON.stringify({ a: 1, b: 2, c: 3, d: { a: [{ y: 8, z: 9 }], j: 7 } }),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { type MaybeRef, get } from '@vueuse/core';
|
||||
import JSON5 from 'json5';
|
||||
|
||||
export { sortObjectKeys, formatJson };
|
||||
|
||||
function sortObjectKeys<T>(obj: T): T {
|
||||
if (typeof obj !== 'object' || obj === null) {
|
||||
return obj;
|
||||
}
|
||||
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map(sortObjectKeys) as unknown as T;
|
||||
}
|
||||
|
||||
return Object.keys(obj)
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.reduce((sortedObj, key) => {
|
||||
sortedObj[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);
|
||||
return sortedObj;
|
||||
}, {} as Record<string, unknown>) as T;
|
||||
}
|
||||
|
||||
function formatJson({
|
||||
rawJson,
|
||||
sortKeys = true,
|
||||
indentSize = 3,
|
||||
}: {
|
||||
rawJson: MaybeRef<string>
|
||||
sortKeys?: MaybeRef<boolean>
|
||||
indentSize?: MaybeRef<number>
|
||||
}) {
|
||||
const parsedObject = JSON5.parse(get(rawJson));
|
||||
|
||||
return JSON.stringify(get(sortKeys) ? sortObjectKeys(parsedObject) : parsedObject, null, get(indentSize));
|
||||
}
|
||||
Reference in new issue
Block a user