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

使用Python上传JSON数据到Firebase时遭遇UnicodeDecodeError错误

解决Python读取JSON文件时的UnicodeDecodeError问题

问题描述

尝试通过Python读取JSON文件并向Firebase上传数据时,遇到编码解码错误,错误信息如下:

Traceback (most recent call last):
  File "c:\Users\isuru\Downloads\CouchMirageFirebaseLoader-master\CouchMirageFirebaseLoader-master\main.py", line 87, in <module>
    main()
  File "c:\Users\isuru\Downloads\CouchMirageFirebaseLoader-master\CouchMirageFirebaseLoader-master\main.py", line 61, in main
    item_data = load_json(path + '/' + index + '/' + collection)
  File "c:\Users\isuru\Downloads\CouchMirageFirebaseLoader-master\CouchMirageFirebaseLoader-master\main.py", line 21, in load_json
    data = json.load(f)
  File "C:\Python310\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Python310\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 114: character maps to <undefined>

错误原因

Windows系统默认使用cp1252编码读取文件,但你的JSON文件实际采用UTF-8编码存储,文件中包含cp1252无法识别的特殊字符,导致解码失败。

解决方案

修改load_json函数,打开文件时显式指定UTF-8编码:

def load_json(file_path):
    # 打开文件时指定UTF-8编码
    with open(file_path, 'r', encoding='utf-8') as f:
        data = json.load(f)
    return data

如果文件编码不确定,或者仍存在编码问题,可以添加错误处理参数,用errors='replace'替换无法识别的字符,避免程序崩溃:

def load_json(file_path):
    with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
        data = json.load(f)
    return data

额外优化建议

  • 路径拼接不要用字符串相加,改用os.path.join,避免跨平台路径问题:
    # 替换原路径拼接代码
    item_data = load_json(os.path.join(path, index, collection))
    
  • 提取glb、json文件时,直接用[0]可能因目录无对应文件报错,建议增加判断:
    model_files = [item_file for item_file in item_files if item_file.endswith('.glb')]
    if not model_files:
        print(f"跳过:{index} 目录下未找到glb模型文件")
        continue
    model = model_files[0]
    
    json_files = [item_file for item_file in item_files if item_file.endswith('.json')]
    if not json_files:
        print(f"跳过:{index} 目录下未找到json文件")
        continue
    collection = json_files[0]
    

内容的提问来源于stack exchange,提问作者Isuru De Silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:54:24