2015-05-19 21 views
9

Yeni etmek python.cursor.Cursor nesneyi dönüştürün. Yani, bir mongodb veritabanından bazı verileri getiriyordum. Ancak, döndürülmüş verilerde json.dumps kullanamadım. İşte benim kod:Pymongo/BSON: serilestirilebilir/JSON nesnesi mongodb ve Python (<code>webapp2</code>) için

exchangedata = db.Stock_Master.find({"Country": "PHILIPPINES"}, {"_id" : 0})   
self.response.write(json.dumps(exchangedata)) 

Bu bir hata atar:

TypeError: pymongo.cursor.Cursor object at 0x7fcd51230290 is not JSON serializable 

exchangedata tipi pymongo.cursor.Cursor olduğunu. Bir json nesnesine nasıl dönüştürebilirim?

+0

İlgili: http://stackoverflow.com/questions/13241878/convert-pymongo-cursor-to-json. – alecxe

+0

İmleci bir nesne listesine dönüştürün: 'self.response.write (json.dumps (liste (exchangedata)))' – Monkpit

+0

Mongo, gerçek bir "liste" yerine bir "imleç" nesnesini döndürür. Bunu Kyle'ın bahsettiği gibi bir 'listeye 'dönüştürmeniz gerekecek. –

cevap

15

Kullanım bson.json_util gelen döker:

>>> 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"}}]' 
+0

Geç cevap için özür dilerim, ama teşekkürler! –

İlgili konular