代码之家  ›  专栏  ›  技术社区  ›  RockScience

JSON序列化Mongodb

  •  35
  • RockScience  · 技术社区  · 12 年前

    我正在使用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(u'日期'、u'名称'等)是什么?

    5 回复  |  直到 6 年前
        1
  •  65
  •   Rafa Viotti aiwiguna    4 年前

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

    from bson.json_util import dumps
    
    dumps(l)
    

    https://pymongo.readthedocs.io/en/stable/api/bson/json_util.html

    侧面回答 : u'name' , u'date' , u'_id' etc是数据库上文档的字段的名称。

        2
  •  13
  •   DhruvPathak    12 年前
    from bson import json_util
    
    
    
    json.dumps(result,default=json_util.default)
    
        3
  •  2
  •   Jackson Jegatheesan    5 年前

    在我的情况下,这个错误是由于烧瓶中的mongo DB id对象造成的 你所要做的就是转换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.collection.find()]
         return jsonify(temp)
    

    同样,来自pymongo的转储也于事无补

    from bson.json_util import dumps,loads
    

    因为它返回的是一个字符串,而不是dict,这在我的情况下是用来创建API的,如果我转储了,我必须再次加载。

        4
  •  1
  •   Jonathan Aspeling    6 年前

    这条线索帮助了我——谢谢你。

    想分享我的最终解决方案,将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,可以根据需要进行编辑。

        5
  •  0
  •   rbansal    8 年前

    我也面临着同样的问题,我编写了一个代码,将文档转换为字典。你可以参考一下。将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