从ZIP文件到MongoDB的Python JSON导入
我有一个脚本,它从一个文件夹中获取所有的.zip文件,然后逐个打开zip文件,在其中加载JSON文件的内容并将其导入MongoDB 我得到的错误是JSON对象必须是str、bytes或bytearray,而不是“TextIOWrapper” 代码是:从ZIP文件到MongoDB的Python JSON导入,python,json,mongodb,Python,Json,Mongodb,我有一个脚本,它从一个文件夹中获取所有的.zip文件,然后逐个打开zip文件,在其中加载JSON文件的内容并将其导入MongoDB 我得到的错误是JSON对象必须是str、bytes或bytearray,而不是“TextIOWrapper” 代码是: import json import logging import logging.handlers import os from logging.config import fileConfig from pymongo import Mongo
import json
import logging
import logging.handlers
import os
from logging.config import fileConfig
from pymongo import MongoClient
def import_json():
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/'
filedir = os.chdir(archive_filepath)
for item in os.listdir(filedir):
if item.endswith('.json'):
file_name = os.path.abspath(item)
fp = open(file_name, 'r')
json_data = json.loads(fp)
for vuln in json_data:
print(vuln)
coll.insert(vuln)
os.remove(file_name)
except Exception as e:
logging.exception(e)
我可以使用一个文件,但不能使用多个文件,即我编写的一个文件:
from zipfile import ZipFile
import json
import pymongo
archive = ZipFile("vulners_collections/cve.zip")
archived_file = archive.open(archive.namelist()[0])
archive_content = archived_file.read()
archived_file.close()
connection = pymongo.MongoClient("mongodb://localhost")
db=connection.vulnerability
vuln1 = db.vulnerability_collection
vulners_objects = json.loads(archive_content)
for item in vulners_objects:
vuln1.insert(item)
通过将迭代器设置为namelist方法的结果,可以重新定义迭代器。您需要for中的for循环来遍历zip文件的内容,当然还需要一个新的迭代器变量。我在上面的评论中:
我没有使用glob的经验,但是通过浏览文档,我得到的印象是,您的归档文件是一个简单的字符串文件路径列表,对吗?您无法执行诸如.open on string之类的操作,从而导致错误,因此请尝试将代码更改为:
...
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)
...
文件不是文件对象或任何东西,只是一个简单的字符串。因此,您无法对其执行字符串不支持的方法。不是file.close错误,正确的调用是file.close 您可以使用json.load直接加载文件,而不是使用json.load
fp = open(file_name, 'r')
json_data = json.load(fp)
fp.close()
尝试替换文件。打开…/使用openfile,rI没有使用glob的经验,但是通过浏览文档,我得到的印象是,您的归档文件是一个简单的字符串文件路径列表,对吗?你不能执行像.open on string这样的操作,这会导致你的错误,所以请尝试使用上面的命令打开文件。这不起作用,我只是得到str'object没有属性'read'的错误。我尝试创建一个新的for循环,但我想我有这个错误:`for file in archive\u files:open\u files=file.openfile.namelist[0]对于open_files中的open_file:file_content=file.read file.close vuln_content=json.loadsfile_content`这让我更进一步,我现在在将编码从UTF8更改为windows-1252时遇到了问题,因为这就是json文件的编码方式。我尝试使用currentFile.encoding='windows-1252',但这只是抛出了一个只读属性error@Luke与openfile一起使用,r,encoding=windows-1252结果我忘了先解压缩文件!但是现在我的脚本运行时没有错误,但是我在MongoDB中什么也没有得到,我添加的print语句也没有做任何事情。我我编辑了代码above@Luke你能给你的输入文件举个例子吗?检查archiveList和vuln_内容的长度,看里面是否有数据。我已经在单独处理ZipFile时更新了代码,并获得了原始的.json文件,所以现在我正在尝试循环这些文件