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

React JS中如何读取Zip包内文件夹名称及内容并提取Python字典转JS对象

解决方案:自动定位Zip包内的__init__.py并解析info字典

核心思路

无需硬编码文件夹名称,通过遍历Zip包内所有文件条目,自动筛选出__init__.py文件,读取内容后将Python风格的字典转换为JS对象。

实现步骤与代码

  1. 遍历Zip条目定位目标文件
    利用JSZip的forEach方法遍历包内所有条目,跳过文件夹,只保留文件名末尾为__init__.py的文件,不管其所在层级。
  2. 转换Python字典为JS对象
    处理Python与JS字典的语法差异(Python用=,JS用:),通过正则提取并转换格式后,用JSON.parse安全解析为JS对象。

完整React组件示例:

import React from 'react';
import JSZip from 'jszip';

function ZipForm() {
  const onChangeFile = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      const zip = await JSZip.loadAsync(file);
      let targetFilePromise = null;

      // 遍历所有条目,定位__init__.py
      zip.forEach((_, entry) => {
        if (!entry.dir && entry.name.endsWith('__init__.py')) {
          targetFilePromise = entry.async('string');
        }
      });

      if (!targetFilePromise) {
        alert('Zip包中未找到__init__.py文件');
        return;
      }

      const pyContent = await targetFilePromise;
      // 提取info字典的核心内容
      const infoMatch = pyContent.match(/info\s*=\s*{([\s\S]*?)}/);
      if (!infoMatch) {
        alert('__init__.py中未找到info字典');
        return;
      }

      // 转换Python语法为JS兼容格式
      const jsCompatibleStr = infoMatch[1]
        .replace(/(\w+)\s*=\s*/g, '$1: ')
        .replace(/'/g, '"');

      // 解析为JS对象
      const infoObj = JSON.parse(`{${jsCompatibleStr}}`);
      console.log('解析完成的info对象:', infoObj);
      // 此处可将infoObj赋值给表单状态,填充到对应输入框
      // setFormData(prev => ({...prev, name: infoObj.name, age: infoObj.age}))

    } catch (err) {
      console.error('Zip包处理失败:', err);
      alert('文件格式有误,请检查后重试');
    }
  };

  return (
    <div>
      <input type="file" accept=".zip" onChange={onChangeFile} />
      <input type="text" placeholder="姓名" />
      <input type="number" placeholder="年龄" />
    </div>
  );
}

export default ZipForm;

关键细节说明

  • 通用定位:遍历逻辑不依赖固定文件夹路径,适配任意层级下的__init__.py文件。
  • 安全解析:用正则提取目标内容后转换语法,再通过JSON.parse解析,避免eval带来的安全风险。
  • 异常处理:覆盖了文件缺失、字典未找到、解析失败等场景,给出明确提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 05:05:21