Insert Multiple JSON files to MongoDB using python

北慕城南 提交于 2020-01-15 11:38:25

问题


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

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"
                ]
            }
        ]
    },.........
}

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

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,

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


回答1:


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


来源:https://stackoverflow.com/questions/59499237/insert-multiple-json-files-to-mongodb-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!