1

如何使用 python 将 Mongo 文档查询集中的数据转储到 .json 文件?

我尝试使用 django 序列化程序,但没有工作,因为在 django 中访问字段的方式与在 mongo 中访问字段的方式相同。

for model in models:
    json_serializer.serialize(model.objects.all(), indent=2, stream=output_file_mongo)

我还尝试使用 python JSON 编码/解码器,

import json
for model in mongo_models:
    output_file_mongo.write(json.dumps(model.objects.all()))

我得到一个例外

  File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
    return _default_encoder.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/lib/python2.7/json/encoder.py", line 178, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [<MongoModelA: MongoModelA object>] is not JSON serializable
4

1 回答 1

2

django 序列化程序不知道如何处理 mongoengine 对象,您很可能必须编写自己的 json 编码器来将它们映射到一个简单的字典:

class MyEncoder(json.JSONEncoder):
    def encode_object(self, obj):
        return { 'id':unicode(obj.id), 'other_property': obj.other_property }

    def default(self, obj):
        if hasattr(obj, '__iter__'):
            return [ self.encode_object(x) for x in obj ]
        else:
            return self.encode_object(obj)

然后这样称呼它:

import json
import MyEncoder

json_string = json.dumps(model.objects.all(), cls=MyEncoder)
于 2011-09-20T16:57:26.123 回答