Question

Background: This works expected:

>>> queryset = FIRM.find_one({'_id':ObjectId("52e56c009dbc794999ea5c3d")},{'wholesalers.name':1,'wholesalers.id':1,'_id':0}) 
>>> simplejson.dumps(queryset,default = json_util.default)
'{"wholesalers": [{"id": {"$oid": "52e56c009dbc794999ea5c3c"}, "name": "wholesaler1"}]}'

BUT this does n't

>>> queryset = FIRM.find({'_id':ObjectId("52e56c009dbc794999ea5c3d")},{'wholesalers.name':1,'wholesalers.id':1,'_id':0}) 
>>> simplejson.dumps(queryset,default = json_util.default)


Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/simplejson-3.3.1-py2.7-linux-i686.egg/simplejson/__init__.py", line 369, in dumps
    **kw).encode(obj)
  File "/usr/local/lib/python2.7/dist-packages/simplejson-3.3.1-py2.7-linux-i686.egg/simplejson/encoder.py", line 262, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/local/lib/python2.7/dist-packages/simplejson-3.3.1-py2.7-linux-i686.egg/simplejson/encoder.py", line 340, in iterencode
    return _iterencode(o, 0)
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.6.3-py2.7-linux-i686.egg/bson/json_util.py", line 220, in default
    raise TypeError("%r is not JSON serializable" % obj)
TypeError: <pymongo.cursor.Cursor object at 0x109774ac> is not JSON serializable

I want to serialize queryset to json

Was it helpful?

Solution

In the first snippet, the object you assign to the variable queryset is a (single) document (find_one returns a document). I.e. a document is fetched from the DB, and stored in memory. A document is json-serializable, so it works.

In the second snippet, the object you assign to queryset is a Cursor. The resulting documents haven't been fetched yet, they are only fetched when you iterate over the cursor. Cursor is not json-serializable, because it does not represent the documents, but a generator of the resulting documents. So what you can do is to first fetch all the documents, and then serialize the list of documents:

>>> queryset = FIRM.find({'_id':ObjectId("52e56c009dbc794999ea5c3d")},{'wholesalers.name':1,'wholesalers.id':1,'_id':0}) 
>>> docs = list(queryset)  # fetch the documents
>>> simplejson.dumps(documents, default = json_util.default)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top