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
1
  • use link for your solution. It should help you. Commented Jan 20, 2014 at 9:01

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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

MyDoc.objects().to_json()
myDoc.to_json()

1 Comment

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": [{}]}]'

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.