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

如何在原生JavaScript中引用JSON文件以提取数据

原生JavaScript加载本地JSON文件的实现方案

方法1:使用fetch() API(推荐,需本地服务器)

这是现代浏览器原生支持的标准方案,需通过本地服务器运行项目(浏览器版VSCode可借助内置的"Live Server"类扩展快速启动)。

步骤:

  1. 确认你的文件结构:
├── index.html
├── script.js
└── objects.json
  1. 在script.js中编写加载逻辑:
// 发起请求加载本地JSON文件
fetch('./objects.json')
  .then(response => {
    // 校验请求状态
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    return response.json(); // 解析返回的JSON数据
  })
  .then(data => {
    // 此处处理获取到的JSON数据
    console.log('已加载的JSON数据:', data);
    // 示例:遍历数据、渲染到页面等操作
  })
  .catch(error => {
    console.error('加载JSON出错:', error);
  });
  1. 在index.html中引入脚本:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>加载本地JSON示例</title>
</head>
<body>
  <script src="./script.js"></script>
</body>
</html>
  1. 在浏览器版VSCode中启动本地服务器:右键点击index.html,选择"Open with Live Server"(需先安装对应扩展),即可正常加载JSON文件。

方法2:使用FileReader API(无需服务器,手动选择文件)

如果无法启动本地服务器,可通过手动选择文件的方式读取JSON,适合快速测试场景:

步骤:

  1. 在index.html中添加文件选择控件:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>读取本地JSON文件</title>
</head>
<body>
  <input type="file" id="jsonFileInput" accept=".json">
  <script src="./script.js"></script>
</body>
</html>
  1. 在script.js中编写读取逻辑:
const fileInput = document.getElementById('jsonFileInput');

fileInput.addEventListener('change', (e) => {
  const selectedFile = e.target.files[0];
  if (!selectedFile) return;

  const reader = new FileReader();
  reader.onload = (event) => {
    try {
      const jsonData = JSON.parse(event.target.result);
      console.log('读取到的JSON数据:', jsonData);
      // 编写数据处理逻辑
    } catch (parseError) {
      console.error('JSON解析失败:', parseError);
    }
  };
  reader.readAsText(selectedFile);
});

重要提示

  • 同源策略限制:直接通过file://协议打开HTML文件时,浏览器会阻止fetch()读取本地文件,必须使用http:///https://协议的本地服务器运行项目,浏览器版VSCode的Live Server扩展可解决此问题。
  • 路径验证:确保fetch()中的文件路径与HTML文件相对位置正确,同目录使用./objects.json,子目录使用./文件夹名/objects.json。

内容的提问来源于stack exchange,提问作者That New Coder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:00:19