简体   繁体   English

如何将json文件加载到mongoDB中?

[英]How do I load a json file into mongoDB?

I have a json file with some information in this format: 我有一个json文件,其中包含以下格式的一些信息:

{ "_id" : ObjectId("xxx"), "date_time" : ISODate("2014-06-11T19:16:45Z"), "name" : "AAA", "phone_no" : "111", "address" : "BBB", "categories" : "CCC" }  
{ "_id" : ObjectId("yyy"), "date_time" : ISODate("2014-06-11T19:16:44Z"), "name" : "EEE", "phone_no" : "222", "address" : "FFF", "categories" : "GGG" }  
{ "_id" : ObjectId("zzz"), "date_time" : ISODate("2014-06-11T19:16:46Z"), "name" : "HHH", "phone_no" : "333", "address" : "III", "categories" : "JJJ" }

The code I'm using is this: 我正在使用的代码是这样的:

db = pymongo.MongoClient().test  
path ='/home/files'  
for f in listdir(path):  
    filepath = path+'/'+f  
    data = []     
    for line in open(filepath):  
        try:  
            data.append(json.loads(line))  
        except:  
            pass  
    db.temp.insert(data)  

This results in an error stating empty bulk write is not possible. 这将导致错误,指出无法进行空批量写入。 Basically, the json.loads(line) never works. 基本上, json.loads(line)永远不会工作。 Is it the format of the json file that's the issue? 这是json文件的格式吗? Should the variable 'data' be declared some other way? 变量“数据”应该以其他方式声明吗?

How do I load this file into mongoDB ? 如何将此文件加载到mongoDB中

json doesnt know what an ObjectID is or an ISODate ... it can only handle simple types... you could try and load the data with yaml if you have defined serialization rules for those clases ... or you can just use simple strings in the line. json不知道什么是ObjectID或ISODate ...它只能处理简单类型...如果为这些分类定义了序列化规则,则可以尝试使用yaml加载数据...或者您可以只使用简单字符串在行中。

for line in open(filepath):
    line = re.sub("[a-zA-Z_]+\(([^)]+)\)","\\1",line)
    print json.loads(line)
    ... #do your thing

this will remove the class calls converting 这将删除类调用转换

{ "_id" : ObjectId("xxx"), "date_time" : ISODate("2014-06-11T19:16:45Z"), "name" : "AAA", "phone_no" : "111", "address" : "BBB", "categories" : "CCC" }  

to

{ "_id":"xxx", "date_time" : "2014-06-11T19:16:45Z", "name" : "AAA", "phone_no" : "111", "address" : "BBB", "categories" : "CCC" }  

which you should then be able to load with json 然后您应该能够使用json加载

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM