gpt4 book ai didi

python - 使用 python 将多个 JSON 文件插入 MongoDB

转载 作者:行者123 更新时间:2023-12-01 06:40:01 25 4
gpt4 key购买 nike

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

每个文件的 json 格式如下:

{
"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 查询时结果显示含义同义词(如果可用)?

我从未使用过 Mongo 来了解如何处理,但对于 mysql 中的单个 json 文件的 SO 建议也做了同样的事情:

**光标有数据库连接

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()

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

但正如建议的那样,我想如果使用 MongoDB,这会变得更好

最佳答案

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

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 - 使用 python 将多个 JSON 文件插入 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59499237/

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