我无法从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'))]"
为什么它没有反序列化对象
答案 0 :(得分:2)
我们假设我在数据库<servlet>
<servlet-name>TheCaptcha</servlet-name>
<servlet-class><servlet>
<servlet-name>StickyCaptcha</servlet-name>
<servlet-class>test.company.something.CaptchaServerServlet</servlet-class>
<init-param>
<param-name>width</param-name>
<param-value>250</param-value>
</init-param>
<init-param>
<param-name>height</param-name>
<param-value>60</param-value>
</init-param>
</servlet>
中有一个集合User
,并希望将其序列化为JSON:
test
如果你想要它在一个文件中:
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