Python JSON 序列化 Mongodb

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19674311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:20:38  来源:igfitidea点击:

JSON serializing Mongodb

pythonmongodbpymongo

提问by RockScience

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

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

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

Then I convert to a list

然后我转换为列表

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

here is what print(l) returns:

这是 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}]

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

现在我需要转换为 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

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

我也曾尝试遵循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  

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

注意:确切地说,我需要使用 R 包 rPython 及其函数 rPython::python.get("l") 将此结果推送到 R

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

附带问题:dict 列表中每个字段之前的 u(u'Date'、u'name' 等)是什么?

采纳答案by Rafa

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:

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

from bson.json_util import dumps

dumps(l)

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

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.

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

回答by DhruvPathak

from bson import json_util



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

回答by rbansal

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.

我遇到了同样的问题,我编写了一个将文档转换为字典的代码。您可以将其用作参考。将 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

回答by Jonathan Aspeling

This thread helped me - thank you.

这个线程帮助了我 - 谢谢。

Wanted to share my final solution to get the JSON back into a JSON/Dictionary Object: (Based on your example)

想分享我的最终解决方案,将 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

Now you have the JSON in a dictionary object and can edit as needed.

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