JSON serializing Mongodb

浪尽此生 提交于 2019-12-02 20:35:12

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

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

from bson import json_util



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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!