【问题标题】:Python JSON encoding errorPython JSON 编码错误
【发布时间】:2017-10-26 10:01:14
【问题描述】:

我有一个 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 中使用了哪种编码?

【问题讨论】:

  • 好吧,你必须在阅读文件之前解压缩文件......你甚至导入了模块但不使用它。
  • 我已经盯着这个看了几个小时.....我完全忘记了添加那个代码!我想我已经把代码弄瞎了!感谢您指出这一点!
  • “新鲜的一双眼睛”......正如他们所说。不客气。
  • 您能否将其作为答案,以便我接受并给予声誉?
  • 完成,谢谢。我还尝试用其他“最佳编程”技巧来证实我的答案。希望他们有所帮助。

标签: python json


【解决方案1】:

请注意,您正在尝试对压缩文件调用 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 步)。

【讨论】:

    猜你喜欢
    • 2020-07-22
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 2015-02-04
    • 2019-09-05
    • 2014-07-17
    • 1970-01-01
    相关资源
    最近更新 更多