【发布时间】:2016-04-16 19:00:05
【问题描述】:
我正在尝试将 mongodb 集合转换为 json 文件,然后将相同的 Json 文件数据加载到另一个 MongoDB 集合。该集合有大约 60,000 行。我写了以下代码:
from pymongo import MongoClient
import json
from bson.json_util import dumps
from bson import json_util
with open("collections/review.json", "w") as f:
l = list(reviews_collection.find())
json.dump(json.dumps(l,default=json_util.default),f,indent = 4)
# reviews_collection_bkp.remove()
reviews_collection_bkp.remove()
with open("collections/review.json") as dataset:
for line in dataset:
data = json.loads(line)
reviews_collection_bkp.insert({
"reviewId": data["reviewId"],
"business": data["business"],
"text": data["text"],
"stars": data['stars'],
"votes":data["votes"]
})
print reviews_collection_bkp.find().count()
review_collection 是我想在 Json 文件名review.json 中写入的集合,稍后我想从同一个文件中读取以将数据插入到 MongoDB 集合中。但我认为代码无法创建正确的 json 文件。因为在读取同一个文件时会产生以下错误:
"reviewId": data["reviewId"],
TypeError: string indices must be integers
为什么创建的 Json 文件格式不正确?
这是line 和data 的示例输出:
"[{\"votes\": {\"funny\": 0, \"useful\": 0, \"cool\": 0}, \"business\": \"wqu7ILomIOPSduRwoWp4AQ\", \"text\": \"Went for breakfast on 6/16/14. We received very good service and meal came within a few minutes.Waitress could have smiled more but was friendly. \\nI had a Grand Slam... it was more than enough food. \\nMeal was very tasty... We will definitely go back. \\nIt is a popular Denny's.\", \"reviewId\": \"0GS3S7UsRGI4B7ziy4cd7Q\", \"stars\": 4, \"_id\": {\"$oid\": \"5711d16fe396f81fcb51dc73\"}},...]
[{"votes": {"funny": 0, "useful": 0, "cool": 0}, "business": "wqu7ILomIOPSduRwoWp4AQ", "text": "Went for breakfast on 6/16/14. We received very good service and meal came within a few minutes.Waitress could have smiled more but was friendly. \nI had a Grand Slam... it was more than enough food. \nMeal was very tasty... We will definitely go back. \nIt is a popular Denny's.", "reviewId": "0GS3S7UsRGI4B7ziy4cd7Q", "stars": 4, "_id": {"$oid": "5711d16fe396f81fcb51dc73"}}......]
【问题讨论】:
-
检查
.json文件时看到了什么?你的data是一个字符串,这就是错误所说的 -
请发布
line和data的样本