You need to enable JavaScript to run this app. 如何使用原生JavaScript读取本地文件夹中的多个JSON文件
优惠活动
大模型
产品
解决方案
定价
更多

如何使用原生JavaScript读取本地文件夹中的多个JSON文件

问题原因

你当前代码的fetch请求写死了路径为data.json,因此只能读取单个固定JSON文件,要读取多个本地JSON文件可按以下两种常见场景修改:

场景1:每个ID对应独立JSON文件

如果你的本地JSON是按ID命名(比如ID为bordeaux对应bordeaux.json,或者统一命名格式为data-${id}.json),直接把fetch路径替换为动态拼接的路径即可,修改后的代码如下:

class App {

    getIdInHash = (slug) => {
        let hash = location.hash,
            hashInArray = hash.split(`#!/${slug}/`),
            id = hashInArray[1];

        return id;
    }

    afficherDetail = (id) => {
        console.log('展示详情');
        // 按你的文件命名规则动态拼接路径,这里示例是id直接作为文件名
        fetch(`${id}.json`)
            .then(function(response) {
                return response.json();
            })
            .then(function(data) {
                console.log(data);
                // 选中空容器
                let elResult = document.querySelector('[data-js-result]');
                // 注入内容
                elResult.innerHTML = `<p>产区${data.region ? data.region : '' }的葡萄品种为:${data.cepage}。</p>`;
            
            })
            .catch(function(error) {
                console.log(`fetch操作出错:${error.message}`);
            });
    };
}

export const { getIdInHash, afficherDetail } = new App();

场景2:需要一次性读取多个无关联的JSON文件

如果你需要同时拉取多个固定JSON(比如region.json、cepage.json、producer.json),可以用Promise.all批量处理fetch请求,示例代码如下:

afficherDetail = async (id) => {
  console.log('展示详情');
  // 把你需要读取的所有JSON路径放进数组
  const fetchFiles = [
    fetch('region.json').then(res => res.json()),
    fetch('cepage.json').then(res => res.json()),
    fetch('producer.json').then(res => res.json())
  ];

  try {
    // 批量等待所有请求返回
    const [regionData, cepageData, producerData] = await Promise.all(fetchFiles);
    let elResult = document.querySelector('[data-js-result]');
    // 按需使用返回的多份JSON数据组装内容
    elResult.innerHTML = `<p>产区${regionData[id].region ? regionData[id].region : '' }的葡萄品种为:${cepageData[id].cepage},对应生产商为${producerData[id].name}。</p>`;
  } catch (error) {
    console.log(`fetch操作出错:${error.message}`);
  }
};

注意事项

  • 本地调试时必须通过本地服务器(比如VS Code的Live Server插件、Nginx、Node服务等)访问页面,直接双击打开HTML文件会触发跨域限制,导致fetch本地文件失败。
  • 如果JSON文件名没有统一规律,你可以先维护一个ID和文件名的映射表,动态读取时通过ID查询对应文件名再拼接路径即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 21:24:03