gpt4 book ai didi

Python:将整个 JSON 目录转换为 Python 字典以发送到 MongoDB

转载 作者:可可西里 更新时间:2023-11-01 10:01:25 26 4
gpt4 key购买 nike

我对 Python 比较陌生,对 MongoDB 也非常陌生(因此,我只关心获取文本文件并进行转换)。我目前正在尝试将一堆 JSON 格式的 .txt 文件移动到 MongoDB 中。因此,我的方法是打开目录中的每个文件,读取每一行,将其从 JSON 转换为字典,然后将 JSON 的行覆盖为字典。然后它将以一种格式发送到 MongoDB

(如果我的推理有任何错误,请指出)

此刻,我写了这个:

"""
Kalil's step by step iteration / write.

JSON dumps takes a python object and serializes it to JSON.
Loads takes a JSON string and turns it into a python dictionary.
So we return json.loads so that we can take that JSON string from the tweet and save it as a dictionary for Pymongo
"""

import os
import json
import pymongo

rootdir='~/Tweets'

def convert(line):
line = file.readline()
d = json.loads(lines)
return d


for subdir, dirs, files in os.walk(rootdir):
for file in files:
f=open(file, 'r')
lines = f.readlines()
f.close()
f=open(file, 'w')
for line in lines:
newline = convert(line)
f.write(newline)
f.close()

但这不是写作。哪个...根据经验,如果您没有获得想要的效果,那您就是在某个地方犯了错误。

有人有什么建议吗?

最佳答案

当您解码一个 json 文件时,您不需要逐行转换,因为解析器会为您遍历该文件(除非您每行有一个 json 文档)。

一旦你加载了 json 文档,你将拥有一个字典,它是一种数据结构,如果不先将其序列化为某种格式,如 json、yaml 或许多其他格式(格式 mongodb使用称为 bson,但您的驱动程序将为您处理编码)。

加载 json 文件并将其转储到 mongo 的整个过程实际上非常简单,看起来像这样:

import json
from glob import glob
from pymongo import Connection

db = Connection().test

for filename in glob('~/Tweets/*.txt'):
with open(filename) as fp:
doc = json.load(fp)

db.tweets.save(doc)

关于Python:将整个 JSON 目录转换为 Python 字典以发送到 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11545291/

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