mongodbコレクションをjsonファイルに変換し、後で同じJsonファイルデータを別のMongoDBコレクションに読み込もうとしています。コレクションには約60,000行があります。私は、次のコードを書かれている:MongoDBコレクションをJsonファイルに変換し、Pythonの同じJsonファイルから読み込みます。
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'は**文字列**です。エラーの内容は – dnit13
です。' line'と 'data'のサンプルを投稿してください。 – Gerrat