JSON序列化Mongodb [英] JSON serializing Mongodb

查看:116
本文介绍了JSON序列化Mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python包pymongo从mongodb数据库中检索数据.

I am using the python package pymongo to retrieve data from a mongodb database.

>>> r = collection.find()   # returns an object of class 'Cursor'

然后我将其转换为列表

>>> l = list(r)             # returns a 'list' of 'dict'

这是print(l)返回的内容:

here is what print(l) returns:

>>> [{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'_id': 1, u'name': u'name1', u'value': 11},{u'date': datetime.datetime(2013, 11, 10, 10, 45), u'_id': 2, u'name': u'name2', u'value': 22}]

现在,我需要转换为JSON,以便可以对其进行操作.

Now I need to convert to JSON so that I can manipulate it.

>>> json.dumps(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python2.7/json/encoder.py", line 178, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2009, 11, 12, 11, 14) is not JSON serializable

我还尝试遵循 http://api .mongodb.org/python/1.7/api/pymongo/json_util.html 没有成功: 链接的最新版本为 http://api.mongodb. org/python/current/api/bson/json_util.html

I have also tried to follow http://api.mongodb.org/python/1.7/api/pymongo/json_util.html without success: the recent version of the link is http://api.mongodb.org/python/current/api/bson/json_util.html

>>> json.dumps(l, default=json_util.default)  
Traceback (most recent call last):  
  File "<stdin>", line 1, in <module>  
NameError: name 'json_util' is not defined  

注意:确切地说,我需要使用R包rPython及其函数rPython :: python.get("l")

Note: precisely I need to push this result to R using the R package rPython and its function rPython::python.get("l")

其他问题:字典列表中每个字段之前的u(u'日期',u'名称'等)是什么?

Side Question: What is the u (u'Date', u'name', etc..) before each field in the list of dict?

推荐答案

您指向的pymongo文档已过时.如果您使用的是1.7版,建议您进行更新.使用更新的版本,您可以执行以下操作:

The pymongo documentation you pointed is obsolete. If you're using version 1.7 I recommend updating. With a more recent version you can do this:

from bson.json_util import dumps

dumps(l)

http://api.mongodb.org/python/current/api/bson/json_util .html

附带答案:u'name'u'date'u'_id'等是数据库上文档字段的名称.

Side answer: u'name', u'date', u'_id' etc are the names of the fields of the document on the database.

这篇关于JSON序列化Mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆