You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JavaScript读取JSON文件显示[Object object]问题求助

解决本地JSON文件读取后显示[Object object]的问题

你遇到的问题核心是:直接把JavaScript对象赋值给innerHTML时,浏览器会默认将对象转为字符串[Object object],而非展示实际内容。以下是两种实用解决方式:

方式一:展示格式化的JSON字符串

将对象转为带缩进的JSON字符串,并用<pre>标签保留格式,让内容清晰可读:

const response = await fetch('./AppData/LocalLow/WilhelmsenStudios/ReEntry/Export/Apollo/outputLGC.json');
let program = await response.json();

document.getElementById('program').innerHTML = `<pre>${JSON.stringify(program, null, 2)}</pre>`;

JSON.stringify的第二个参数null表示保留所有属性,第三个参数2表示用2个空格做缩进,优化排版。

方式二:自定义HTML结构展示

如果想要更友好的展示形式(比如键值对列表),可以手动遍历对象属性构建HTML:

const response = await fetch('./AppData/LocalLow/WilhelmsenStudios/ReEntry/Export/Apollo/outputLGC.json');
let program = await response.json();

const container = document.getElementById('program');
container.innerHTML = '';

// 处理对象类型的program
if (typeof program === 'object' && !Array.isArray(program)) {
    for (const [key, value] of Object.entries(program)) {
        const item = document.createElement('div');
        // 嵌套对象也转成格式化字符串
        item.innerHTML = `<strong>${key}:</strong> ${typeof value === 'object' ? `<pre>${JSON.stringify(value, null, 2)}</pre>` : value}`;
        container.appendChild(item);
    }
} 
// 处理数组类型的program
else if (Array.isArray(program)) {
    const list = document.createElement('ul');
    program.forEach((item, index) => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `<strong>项${index+1}:</strong> ${typeof item === 'object' ? `<pre>${JSON.stringify(item, null, 2)}</pre>` : item}`;
        list.appendChild(listItem);
    });
    container.appendChild(list);
}

额外注意:如果是通过file://协议直接打开本地HTML文件,部分浏览器可能限制fetch读取本地文件,此时可以搭建简单本地服务器(比如Python的python -m http.server或Node.js的http-server)运行网站,规避跨域限制。

内容的提问来源于stack exchange,提问作者Swap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:35:49