我想将django ORM返回的mogodb对象序列化为json,以便我可以直接将它传递给模板。
这是我的mongodb文件:公司
{
"_id" : ObjectId("52d983139dbc7913f25c9e05"),
"type" : "R",
"users" : [{ "name" : "praveen",
"pwd" : "hola",
"draft_items" : [
{
"name" : "DICLOP",
"manu" : "RANBAXY",
}
}],
}
我尝试了这个,但我只获得了关键而不是价值:
>>> from bson.json_util import dumps
>>> x = firm.objects.get()
>>> dumps(x)
["id", "name", "type", "users"]
我也试过
>>> 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
答案 0 :(得分:1)
你可以使用dir()来查看obj属性。 你可以使用to_json func来序列化mongodb对象
>>> x = firm.objects.get(_id=ObjectId("52d983139dbc7913f25c9e05"))
>>> print x.to_json()
答案 1 :(得分:0)
您应该在查询集或文档上使用to_json
,例如:
MyDoc.objects().to_json()
myDoc.to_json()