使用python将多个JSON文件插入MongoDB [英] Insert Multiple JSON files to MongoDB using python

查看:387
本文介绍了使用python将多个JSON文件插入MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSON文件如下a.json,b.json ..... z.json(26个json文件)

The JSON files are as follows a.json,b.json.....z.json (26 json files)

每个文件的json格式如下:

The json format of each of the file looks as:

{
    "a cappella": {
        "word": "a cappella",
        "wordset_id": "5feb6f679a",
        "meanings": [
            {
                "id": "492099d426",
                "def": "without musical accompaniment",
                "example": "they performed a cappella",
                "speech_part": "adverb"
            },
            {
                "id": "0bf8d49e2e",
                "def": "sung without instrumental accompaniment",
                "example": "they sang an a cappella Mass",
                "speech_part": "adjective"
            }
        ]
    },
    "A.D.": {
        "word": "A.D.",
        "wordset_id": "b7e9d406a0",
        "meanings": [
            {
                "id": "a7482f3e30",
                "def": "in the Christian era",
                "speech_part": "adverb",
                "synonyms": [
                    "AD"
                ]
            }
        ]
    },.........
}

如何将它们存储在MongoDB中,以便如果使用word查询,结果将显示meaningssynonyms(如果可用)?

How could I store these in MongoDB such that if queried with word the results shows meanings,synonyms(if available)?

我从未在方法上使用过Mongo,但是对mysql中单个json文件的SO建议也是如此:

I have never used Mongo on how to approach, but the same was done with SO suggestions for a single json file in mysql as:

**光标具有数据库连接

**cursor has db connection

with open('a.json') as f:
    d = json.load(f)

for word in d:
    word_obj = d[word]
    wordset_id = word_obj['wordset_id']

    sql = "INSERT INTO Word (word, wordset_id) VALUES (%s, %s)"
    values = (word, wordset_id)
    cursor.execute(sql, values)
    conn.commit()

类似于将含义和同义词存储在不同的表中,

similarly to store meanings and synonyms as different tables,

但是建议,如果使用MongoDB,这会变得更好

But as suggetsed I guess this would become better if MongoDB is used

推荐答案

如果要从多个.json文件插入数据,请循环执行:

If you want to insert data from multiple .json files, do it in a loop:

file_names = ['a.json', 'b.json', ...]

for file_name in file_names:
    with open(file_name) as f:
        file_data = json.load(f)  # load data from JSON to dict
        for k, v in file_data.items():  # iterate over key-value pairs
            collection.insert_one(v)  # your collection object here

这篇关于使用python将多个JSON文件插入MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆