我想阅读一个JSON文件,并在Python中将它的每个文档插入到mongodb中。
代码是:
#!flask/bin/python
import json;
import csv;
import bson;
from pymongo import MongoClient
#connect to database
c = MongoClient('localhost',27017)
db = c.wsn
nodeInfo = db.nodeInfo;
table = db.table;
limit = 0;
skip = 0;
results = [];
#To be able to read csv formated files, we will first have to import the
#csv module.
with open('data.csv', 'rb') as f:
reader = csv.reader(f)
obj = [];
for row in reader:
for field in row:
print(field);
nodeInfo.insert_one(field);
File data is like :
{"name" : "A"}
{"name" : "B"}
{"name" : "C"}
我收到此错误:
TypeError:document必须是dict,bson.son.SON,bson.raw_bson.RawBSONDocument的实例,或者是从collections.MutableMapping继承的类型
答案 0 :(得分:0)
您的输入数据根本不像csv
,不确定为什么使用csv
模块来阅读它。
看起来你在文件的每一行都有JSON字符串。逐行读取文件,使用json.loads()
加载并插入:
import json
with open('input_file.txt', 'rb') as f:
for row in f:
nodeInfo.insert_one(json.loads(row))