4

Trying to serialize a MongoDB cursor in Django

import json
from pymongo import json_util

results = json.dumps(results, default=json_util.default, separators=(',', ':'))

Where the original results is something like

[{u'_id': ObjectId('4f7c0f34705ff8294a00006f'),
  u'identifier': u'1',
  u'items': [{u'amount': 9.99, u'name': u'PapayaWhip', u'quantity': 1}],
  u'location': None,
  u'timestamp': datetime.datetime(2012, 4, 4, 10, 7, 0, 596000),
  u'total': 141.25}]

Edit: Obtained by using something like

from django.db import connections

connection = connections['default']

results = connection.get_collection('papayas_papaya')
results = results.find({
    'identifier': '1',
})

Gives me

TypeError: <django_mongodb_engine.utils.DebugCursor object> is not JSON serializable

Does anyone know what I'm doing wrong?

Using json_util should serialize MongoDB documents, maybe my issue is that I'm trying to serliaze a cursor. (How do I get the document from the cursor? A simple tuple "cast"?)

Cheers!

2
  • In order to help you we're gonna need to at least see what code you run to obtain result. Commented Apr 16, 2012 at 10:50
  • @NolenRoyalty I already showed what results looks like; to obtain it I used regular PyMongo query. I've updated the question anyway :-) Commented Apr 16, 2012 at 10:56

2 Answers 2

5

Are you trying to serialize just one piece of data? If so, just change

results = results.find({
    'identifier': '1',
})

to

results = results.find_one({
    'identifier': '1',
})

(Although you really should make a distinction between your results and the variable representing your collection.)

If you are trying to serialize multiple pieces of data, you can keep the find and then iterate through the cursor and serialize each piece of data.

serialized_results = [json.dumps(result, default=json_util.default, separators=(',', ':')) for result in results]
Sign up to request clarification or add additional context in comments.

1 Comment

Ended up casting the cursor to a tuple and JSON-dumping that. Thanks for your help :-)
0

You should really be using Django's serialization system, or a pluggable JSON-serialization app at least.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.