JSON serializing Mongodb

后端 未结 5 1479
南笙
南笙 2020-12-05 05:10

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

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


        
5条回答
  •  余生分开走
    2020-12-05 05:17

    I was facing the same issue, I wrote a code that converts document to dictionary. You can use that for reference. Pass the object obtained by find_one() into documentToJson() method and the results of find() into convertDocumentsToJson. There is type in the name Json, instead the code converts to Dict rather than 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
    

提交回复
热议问题