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

如何在JS中从textarea或本地文件获取并处理JSON数据

无需服务器的本地JSON文件处理方案

可以通过浏览器原生的FileReader API实现本地文件读取与解析,完全不需要搭建服务器,也不用把JSON硬编码进JS文件,具体实现如下:

核心实现思路

  • 用文件选择控件让用户主动选择本地的JSON/文本文件
  • 监听文件选择事件,通过FileReader读取文件内容
  • 将读取到的文本解析为JSON对象
  • 执行筛选逻辑提取目标数据

完整代码示例

<!DOCTYPE html>
<html>
<body>
  <input type="file" id="fileInput" accept=".txt,.json">
  <div id="result"></div>

  <script>
    const fileInput = document.getElementById('fileInput');
    const resultDiv = document.getElementById('result');

    fileInput.addEventListener('change', handleFileSelect);

    function handleFileSelect(event) {
      const file = event.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = function(e) {
        try {
          // 把读取到的文本解析为JSON对象
          const cc = JSON.parse(e.target.result);
          // 执行你的筛选逻辑
          const idToLookFor = true;
          const addrs = cc.res
            .filter(item => item.default === idToLookFor)
            .map(elem => elem.add)
            .join(",");
          
          // 展示结果
          resultDiv.textContent = `筛选结果:${addrs}`;
          console.log(addrs);
        } catch (error) {
          resultDiv.textContent = '文件解析错误,请确保是合法的JSON格式';
          console.error('JSON解析失败:', error);
        }
      };
      // 以文本形式读取文件内容
      reader.readAsText(file);
    }
  </script>
</body>
</html>

关键说明

  1. FileReader API:这是浏览器原生提供的能力,允许读取用户主动选择的本地文件,不会触发CORS限制——因为是用户主动授权的操作,不属于跨域请求范畴
  2. JSON解析步骤:读取到的文件内容是字符串,必须用JSON.parse()转换成对象后才能访问res属性,这是你之前代码返回undefined的核心原因(直接操作字符串而非JSON对象)
  3. 错误处理:加入try-catch可以处理JSON格式错误的情况,避免页面崩溃,同时给用户明确提示

替代方案:使用textarea输入JSON

如果不想用文件选择,也可以用textarea让用户粘贴JSON内容,逻辑类似:

<!DOCTYPE html>
<html>
<body>
  <textarea id="jsonInput" rows="10" cols="50"></textarea>
  <button onclick="processJson()">处理数据</button>
  <div id="result"></div>

  <script>
    function processJson() {
      const jsonText = document.getElementById('jsonInput').value;
      if (!jsonText) return;

      try {
        const cc = JSON.parse(jsonText);
        const idToLookFor = true;
        const addrs = cc.res
          .filter(item => item.default === idToLookFor)
          .map(elem => elem.add)
          .join(",");
        
        document.getElementById('result').textContent = `筛选结果:${addrs}`;
        console.log(addrs);
      } catch (error) {
        document.getElementById('result').textContent = '输入的JSON格式无效';
        console.error('JSON解析失败:', error);
      }
    }
  </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:35:58