本文介绍了Pymongo/bson:将python.cursor.Cursor对象转换为可序列化/JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
MongoDb和Python(webapp2
)的新功能.因此,我正在从 mongodb 数据库中获取一些数据.但是我无法对返回的数据使用json.dumps
.这是我的代码:
New to MongoDb and Python (webapp2
). So, I was fetching some data from a mongodb database. But I was unable to use json.dumps
on the returned data. Here's my code:
exchangedata = db.Stock_Master.find({"Country": "PHILIPPINES"}, {"_id" : 0})
self.response.write(json.dumps(exchangedata))
这会引发错误:
TypeError: pymongo.cursor.Cursor object at 0x7fcd51230290 is not JSON serializable
exchangedata
的类型是pymongo.cursor.Cursor
.如何将其转换为json对象?
The type of exchangedata
is pymongo.cursor.Cursor
. How can I convert it into a json object?
推荐答案
使用来自 bson.json_util :
>>> c = pymongo.MongoClient()
>>> c.test.test.count()
5
>>> from bson.json_util import dumps
>>> dumps(c.test.test.find())
'[{"_id": {"$oid": "555cb3a7fa5bd85b81d5a624"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a625"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a626"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a627"}}, {"_id": {"$oid": "555cb3a7fa5bd85b81d5a628"}}]'
这篇关于Pymongo/bson:将python.cursor.Cursor对象转换为可序列化/JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!