0

I want to serialize mogodb object which is returned by django ORM to json so that I can pass it to template directly.

Here is my mongodb document :firm

{
    "_id" : ObjectId("52d983139dbc7913f25c9e05"),
    "type" : "R",
    "users" : [{    "name" : "praveen",
                    "pwd" : "hola",
                    "draft_items" : [
                     {
                         "name" : "DICLOP",
                         "manu" : "RANBAXY",
                     }
             }],


}

I tried this but I only get key not the value :

>>> from bson.json_util import dumps
>>> x = firm.objects.get()
>>> dumps(x)
["id", "name", "type", "users"]

I also tried

    >>> from bson import json_util
    >>> import json

    >>> json.dumps(x,default=json_util.default)

    Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 264, 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: <firm: firm object> is not JSON serializable
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Praveen Singh Yadav
  • 1,831
  • 4
  • 20
  • 31
  • use [link](http://stackoverflow.com/questions/6255387/mongodb-object-serialized-as-json) for your solution. It should help you. – Aks Jan 20 '14 at 09:01

2 Answers2

2

you can use dir() to see obj property. you can use to_json func for serialize mongodb object

>>> x = firm.objects.get(_id=ObjectId("52d983139dbc7913f25c9e05"))
>>> print x.to_json()
zweite
  • 21
  • 3
0

You should use to_json either on the queryset or the document eg:

MyDoc.objects().to_json()
myDoc.to_json()
Ross
  • 17,861
  • 2
  • 55
  • 73
  • Thanks for mongoengine. when I try projection like following firm.objects(__raw__={'_id': x}).only('wholesalers'), I get result but when I try firm.objects(__raw__={'_id':x}).only('wholesalers').to_json() it gives a blank dict '[{"wholesalers": [{}]}]' – Praveen Singh Yadav Jan 20 '14 at 16:18