JSON序列化Mongodb

时间:2013-10-30 05:09:46

标签: python mongodb pymongo rpython

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

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

然后我转换为列表

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

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

>>> [{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以便我可以操作它。

>>> 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

>>> 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”)

将此结果推送到R

旁边问题:在dict列表中的每个字段之前,你(u'Date',u'name'等等)是什么?

5 个答案:

答案 0 :(得分:43)

您指出的pymongo文档已过时。如果您使用的是1.7版,我建议您更新。使用更新版本,您可以执行此操作:

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'等是数据库中文档字段的名称。

答案 1 :(得分:11)

from bson import json_util



json.dumps(result,default=json_util.default)

答案 2 :(得分:1)

在我的情况下,此错误是由于烧瓶中的mongo DB ID对象引起的 您需要做的就是转换id(如果需要),否则也可以将其弹出 我正在分享我的解决方案,我希望这对某人有帮助

from flask import jsonify

def get_data(self,data):
     data['_id'] = str(data['_id'])
     return data

app =  Flask(__name__)

@app.route('/')
def apimethod():
     temp = [self.get_data(i) for i in self.critical.find()]
     return jsonify(temp)

从pymongo转储也无济于事

from bson.json_util import dumps,loads

因为它返回的是字符串,而不是根据我的情况创建API的字典,所以如果我转储,则必须再次加载。

答案 3 :(得分:0)

我遇到了同样的问题,我编写了将文档转换为字典的代码。您可以将其用作参考。将find_one()获得的对象传递给documentToJson()方法,并将find()的结果传递给convertDocumentsToJson。名称为Json的类型,而不是代码转换为Dict而不是json。

from bson.json_util import dumps

class UtilService:

def __init__(self):
    pass

@staticmethod
def pinCodeParser(path):
    location = {}
    f = open(path)
    for line in f:
        words = line.split()
        location[words[1]] = (words[-3],words[-2])
    return location

@staticmethod
def listHelper(str):
    s = []
    str = str.split(',')
    for e in str:
        s.append(e.replace("[","").replace("]",""))
    return s

@staticmethod
def parseList(str):
    if ',' in str:
        return UtilService.listHelper(str)
    return str

@staticmethod
def trimStr(str):
    return str.replace('"','')

@staticmethod
def documentToJson(document):
    document = eval(dumps(document))
    mp = {}
    for key, value in document.iteritems():
        if "_id" in key:
            mp["id"] = str(value["$oid"])
        else:
            mp[ UtilService.trimStr(key) ] = UtilService.parseList( value )
    return mp

@staticmethod
def convertDocumentsToJson(documents):
    result = []
    for document in documents:
        result.append(UtilService.documentToJson(document))
    return result

答案 4 :(得分:0)

该主题对我有所帮助-谢谢。

想分享我的最终解决方案,以将JSON返回JSON / Dictionary对象:(基于您的示例)

from bson.json_util import dumps, loads
r = collection.find()
l = list(r) # Converts object to list
d = dumps(l) # Converts to String
dict_needed = loads(d[0]) # Serializes String and creates dictionary

现在,您在字典对象中具有JSON,并且可以根据需要进行编辑。