如何在前端页面上展示解析后的 JSON 数据?
在前端页面展示解析后的 JSON 数据通常需要以下步骤:解析数据、格式化结构、创建 DOM 元素、应用样式。以下是几种常见的实现方式及示例:
方法 1:简单文本展示(基础方法)
直接将 JSON 对象转为格式化字符串显示:
// 假设已解析 JSON 数据
const jsonData = {timestamp: 1628323200000,type: "data",content: {cmd: "f005",data: 4,action: "fallocate -l 200M /tmp/test1.txt"}
};// 转为格式化字符串(缩进 2 个空格)
const formattedJson = JSON.stringify(jsonData, null, 2);// 创建 pre 元素展示代码
const preElement = document.createElement('pre');
preElement.textContent = formattedJson;
document.body.appendChild(preElement);
优点:简单直接,保留原始结构
缺点:样式单调,缺乏交互性
方法 2:表格展示(适合结构化数据)
将 JSON 转换为表格形式:
function jsonToTable(jsonData) {const table = document.createElement('table');table.className = 'w-full border-collapse';// 创建表头const thead = document.createElement('thead');const headerRow = document.createElement('tr');Object.keys(jsonData).forEach(key => {const th = document.createElement('th');th.className = 'border p-2 bg-gray-100';th.textContent = key;headerRow.appendChild(th);});thead.appendChild(headerRow);table.appendChild(thead);// 创建表体const tbody = document.createElement('tbody');const row = document.createElement('tr');Object.values(jsonData).forEach(value => {const td = document.createElement('td');td.className = 'border p-2';td.textContent = typeof value === 'object' ? JSON.stringify(value) : value;row.appendChild(td);});tbody.appendChild(row);table.appendChild(tbody);return table;
}// 使用示例
document.body.appendChild(jsonToTable(jsonData));
优点:数据清晰,适合比较多行记录
缺点:嵌套结构显示效果差
方法 3:卡片式分层展示(推荐)
将 JSON 转换为具有视觉层次的卡片组件:
function renderJsonAsCards(jsonData) {const container = document.createElement('div');container.className = 'max-w-4xl mx-auto p-4 space-y-4';// 遍历 JSON 顶级键值对Object.entries(jsonData).forEach(([key, value]) => {const card = document.createElement('div');card.className = 'bg-white rounded-lg shadow-md p-4 transition-all duration-300 hover:shadow-lg';// 标题行const title = document.createElement('h3');title.className = 'text-lg font-semibold mb-2 text-primary';title.textContent = key;card.appendChild(title);// 值内容const content = document.createElement('div');content.className = 'ml-2';if (typeof value === 'object' && value !== null) {// 嵌套对象:递归生成子卡片const nestedContainer = document.createElement('div');nestedContainer.className = 'space-y-3 mt-2 pl-4 border-l-2 border-gray-200';Object.entries(value).forEach(([nestedKey, nestedValue]) => {const nestedCard = document.createElement('div');nestedCard.className = 'bg-gray-50 rounded p-3';const nestedTitle = document.createElement('p');nestedTitle.className = 'font-medium text-gray-700';nestedTitle.textContent = nestedKey;nestedCard.appendChild(nestedTitle);const nestedContent = document.createElement('p');nestedContent.className = 'text-gray-600 mt-1';nestedContent.textContent = JSON.stringify(nestedValue);nestedCard.appendChild(nestedContent);nestedContainer.appendChild(nestedCard);});content.appendChild(nestedContainer);} else {// 普通值:直接显示const valueElement = document.createElement('p');valueElement.className = 'text-gray-600';valueElement.textContent = String(value);content.appendChild(valueElement);}card.appendChild(content);container.appendChild(card);});return container;
}// 使用示例
document.body.appendChild(renderJsonAsCards(jsonData));
优点:视觉层次清晰,适合复杂嵌套结构
缺点:代码量较大
方法 4:交互式树形视图(高级方案)
使用第三方库(如 react-json-view
或自定义实现)创建可折叠的树形视图:
function createJsonTree(jsonData, parentElement = null) {const ul = document.createElement('ul');ul.className = 'list-none pl-4';Object.entries(jsonData).forEach(([key, value]) => {const li = document.createElement('li');li.className = 'my-1';// 键名const keySpan = document.createElement('span');keySpan.className = 'font-medium text-primary';keySpan.textContent = `${key}: `;li.appendChild(keySpan);if (typeof value === 'object' && value !== null) {// 对象/数组:创建可折叠节点const toggleBtn = document.createElement('button');toggleBtn.className = 'text-gray-500 hover:text-gray-700 focus:outline-none';toggleBtn.innerHTML = '<i class="fa fa-chevron-down mr-1"></i>';const valueSpan = document.createElement('span');valueSpan.className = 'text-gray-600 cursor-pointer';valueSpan.textContent = Array.isArray(value) ? '[...]' : '{...}';const childTree = createJsonTree(value);childTree.style.display = 'none';toggleBtn.addEventListener('click', () => {const isVisible = childTree.style.display === 'block';childTree.style.display = isVisible ? 'none' : 'block';toggleBtn.innerHTML = isVisible ? '<i class="fa fa-chevron-down mr-1"></i>' : '<i class="fa fa-chevron-up mr-1"></i>';});li.appendChild(toggleBtn);li.appendChild(valueSpan);li.appendChild(childTree);} else {// 普通值:直接显示const valueSpan = document.createElement('span');valueSpan.className = 'text-gray-600';// 根据类型设置不同样式if (typeof value === 'string') {valueSpan.className += ' text-green-600';valueSpan.textContent = `"${value}"`;} else if (typeof value === 'number') {valueSpan.className += ' text-blue-600';valueSpan.textContent = value;} else if (typeof value === 'boolean') {valueSpan.className += ' text-purple-600';valueSpan.textContent = value;} else if (value === null) {valueSpan.className += ' text-gray-400';valueSpan.textContent = 'null';}li.appendChild(valueSpan);}ul.appendChild(li);});if (parentElement) {parentElement.appendChild(ul);}return ul;
}// 使用示例
document.body.appendChild(createJsonTree(jsonData));
优点:交互性强,适合深度嵌套的复杂 JSON
缺点:实现复杂度高,需处理折叠 / 展开逻辑
方法 5:使用 Tailwind CSS 美化展示(推荐)
结合 Tailwind CSS 实现现代化的卡片式展示:
<style type="text/tailwindcss">@layer utilities {.json-key {@apply font-medium text-primary;}.json-string {@apply text-green-600;}.json-number {@apply text-blue-600;}.json-boolean {@apply text-purple-600;}.json-null {@apply text-gray-400;}.json-toggle {@apply text-gray-500 hover:text-gray-700 focus:outline-none transition-transform duration-200;}}
</style><div class="max-w-4xl mx-auto p-4 space-y-4"><div class="bg-white rounded-xl shadow-lg overflow-hidden"><div class="p-6"><h2 class="text-xl font-semibold mb-4">JSON 数据展示</h2><div id="json-display" class="space-y-3"></div></div></div>
</div><script>function renderJsonWithTailwind(jsonData, parentElement) {const container = document.createElement('div');Object.entries(jsonData).forEach(([key, value]) => {const item = document.createElement('div');item.className = 'p-3 border-b border-gray-100 last:border-0';// 键名const keyElement = document.createElement('div');keyElement.className = 'json-key mb-1';keyElement.textContent = key;// 值const valueElement = document.createElement('div');valueElement.className = 'ml-4';if (typeof value === 'object' && value !== null) {// 嵌套对象const nestedContainer = document.createElement('div');nestedContainer.className = 'mt-2 pl-4 border-l-2 border-gray-100';// 折叠/展开按钮const toggleBtn = document.createElement('button');toggleBtn.className = 'json-toggle flex items-center';toggleBtn.innerHTML = '<i class="fa fa-chevron-down mr-2"></i> 显示详情';const nestedContent = document.createElement('div');nestedContent.className = 'mt-2 hidden';renderJsonWithTailwind(value, nestedContent);toggleBtn.addEventListener('click', () => {const isVisible = nestedContent.classList.contains('hidden');nestedContent.classList.toggle('hidden');toggleBtn.innerHTML = isVisible ? '<i class="fa fa-chevron-up mr-2"></i> 隐藏详情' : '<i class="fa fa-chevron-down mr-2"></i> 显示详情';toggleBtn.querySelector('i').classList.toggle('rotate-180', isVisible);});valueElement.appendChild(toggleBtn);valueElement.appendChild(nestedContent);} else {// 普通值const valueSpan = document.createElement('span');if (typeof value === 'string') {valueSpan.className = 'json-string';valueSpan.textContent = `"${value}"`;} else if (typeof value === 'number') {valueSpan.className = 'json-number';valueSpan.textContent = value;} else if (typeof value === 'boolean') {valueSpan.className = 'json-boolean';valueSpan.textContent = value;} else if (value === null) {valueSpan.className = 'json-null';valueSpan.textContent = 'null';} else {valueSpan.textContent = value;}valueElement.appendChild(valueSpan);}item.appendChild(keyElement);item.appendChild(valueElement);container.appendChild(item);});if (parentElement) {parentElement.appendChild(container);}return container;}// 使用示例const jsonDisplay = document.getElementById('json-display');renderJsonWithTailwind(jsonData, jsonDisplay);
</script>
优点:美观现代,交互友好,适合生产环境
缺点:需要引入 Tailwind CSS
关键技术要点
1)安全解析 JSON:使用 JSON.parse()
,并添加错误处理
2)递归处理嵌套结构:对对象和数组进行递归解析
3)类型区分:根据值的类型(字符串、数字、布尔值等)应用不同样式
4)交互增强:添加折叠 / 展开功能,提升大数据查看体验
5)视觉优化:使用卡片、边框、缩进等创建视觉层次