【问题标题】:Unable to deserialize Pymongo ObjectId and DateTime from JSON无法从 JSON 反序列化 Pymongo ObjectId 和 DateTime
【发布时间】:2017-06-25 21:02:21
【问题描述】:

我无法从 MongoDB Json 文档中反序列化 ObjectId() 和 datetime()。

我的 MongoDB Json 文档如下:

result = "[(u'profileDetails', {u'basicDetails': {u'dateOfBirth': datetime.datetime(1992, 2, 1, 0, 0), u'customerCode': u'C037799'}, u'xDirLevel': {u'masterCode': 1}}), (u'_id', ObjectId('58872e99321a0c8633291b3f'))]"

我想反序列化 datetime() 和 ObjectId() 函数。

我的 Python 代码如下:

from bson import json_util

def deserialize_mongoResult(mongoResult)
   result = json.dumps(mongoResult, default=json_util.default)
   print result

当我打印result 时,如下所示:

"[(u'profileDetails', {u'basicDetails': {u'dateOfBirth': datetime.datetime(1992, 2, 1, 0, 0), u'customerCode': u'C037799'}, u'xDirLevel': {u'masterCode': 1}}), (u'_id', ObjectId('58872e99321a0c8633291b3f'))]"

为什么不反序列化对象

【问题讨论】:

  • 反序列化 datetime() 和 ObjectId() 函数是什么意思?你的预期输出是什么?
  • 我希望 ObjectId() 和 datetime() 函数不应该出现在结果中。我发现json_util 会达到目的,但使用后结果不会改变。我在stackoverflow中发现了同样的问题,我在那里问了同样的问题,他们建议打开新问题same like question in stackoverflow
  • @arthur,我希望 ObjectId() 值应该更改为 {"_id": {"$oid": "4edebd262ae5e93b41000000"}} 和 datetime() 函数我不确定,它应该转换为 json 格式
  • 好的,所以我假设您有一个来自 pymongo 的文档,并且您希望它是一个 JSON 文件,所以您想要 serialize 它。我说的对吗?
  • 是的,你是对的亚瑟

标签: python


【解决方案1】:

假设我在数据库 test 中有一个集合 User 并希望将其序列化为 JSON:

import pymongo
from bson.json_util import dumps
client = pymongo.MongoClient()
db = client.test
user = db["user"]
# I query the database to get one user : 
res = user.find_one({"country": "us"})
In [66]: res
Out[66]: 
{u'_id': ObjectId('5880fa045fa6a6ffa97a82c7'),
 u'date': datetime.datetime(1992, 2, 1, 0, 0),
 u'name': u'steve',
 u'country': u'us'}
In [63]: dumps(res)
Out[63]: '{"country": "us", "_id": {"$oid": "5880fa045fa6a6ffa97a82c7"}, "name": "steve", "date": {"$date": 696902400000}}'

如果你想在一个文件中:

import json
with open("myfile.json", "w") as f:
    json.dump(dumps(res),f)

现在,如果您无法修改 result 格式,您仍然可以这样做:

import datetime
from bson.json_util import dumps
from bson.objectid import ObjectId

#transform string to list    
result = eval(result)
result_dict = dict(result)
dumps(result_dict)
Out[79]: '{"profileDetails": {"basicDetails": {"dateOfBirth": {"$date": 696902400000}, "customerCode": "C037799"}, "xDirLevel": {"masterCode": 1}}, "_id": {"$oid": "58872e99321a0c8633291b3f"}}'

【讨论】:

  • 还有一个小查询,date 来自 696902400000 如何将此日期值转换为普通日期,如 dd-mm-yyyyyyyy-mm-dd 格式。
  • result_dict["date"] = datetime.datetime.strftime(result_dict["date"] , format="%Y-%m-%d")
猜你喜欢
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多