如何使用 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