gpt4 book ai didi

Python JSON 编码错误

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:56 25 4
gpt4 key购买 nike

我有一个 Python 脚本来读取 JSON 文件的内容并导入到 MongoDB。

我从中收到以下错误:

Traceback (most recent call last):
File "/home/luke/projects/vuln_backend/vuln_backend/mongodb.py", line 39, in process_files
file_content = currentFile.read()
File "/home/luke/envs/vuln_backend/lib64/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 14: invalid continuation byte

这是代码:

import json
import logging
import logging.handlers
import os
import glob
from logging.config import fileConfig
from zipfile import ZipFile
from pymongo import MongoClient


def process_files():
try:
client = MongoClient('5.57.62.97', 27017)
db = client['vuln_sets']
coll = db['vulnerabilities']
basepath = os.path.dirname(__file__)
filepath = os.path.abspath(os.path.join(basepath, ".."))
archive_filepath = filepath + '/vuln_files/'
archive_files = glob.glob(archive_filepath + "/*.zip")

for file in archive_files:
with open(file, "r") as currentFile:
file_content = currentFile.read()
vuln_content = json.loads(file_content)
for item in vuln_content:
coll.insert(item)
except Exception as e:
logging.exception(e)

我尝试将编码设置为 UTF8 和 Windows-1252,但这些似乎也无法读取 JSON。

如何让它确定 JSON 中使用哪种编码?

最佳答案

请注意,您正在尝试对压缩文件调用 json.load。您必须首先使用 zipfile 模块解压缩它,如下所示:

with open ZipFile(file, 'r') as f:
f.extractall(dest)

其中file是循环变量。

此外,在读取 JSON 文件时,我建议使用 json.load(fileobj) (1 步),而不是读取文件内容并调用 json.loads(string_from_file) 在字符串中(2 个步骤)。

关于Python JSON 编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com