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

标签 python json mongodb

我对 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/

相关文章:

python - 将原始 SQL 查询转换为 Django QuerySet

python - 如何搜索音频文件中的内容?

python - PyMongo json_util.dumps 覆盖 ObjectId 表示

python - 以 Float 形式表示的年份到 Datetime64

Python 3 : UnboundLocalError - local variable referenced before assignment

java - 当使用 Spring Boot Rest Controller 中的其他实体引用映射到 Hibernate 实体的 JSON 时,Jackson InvalidTypeIdException

MongoDB - 使用多个参数从多个集合中搜索

php - 迭代 mongodb 查询返回的数组

json - 'oneof' protobuf 字段的预期 JSON 序列化是什么?

使用 Big Huge Thesaurus API 时出现 Python 错误