1
如何將Mongo文檔的查詢集中的數據轉儲爲使用python的.json文件?將mongoengine查詢集轉換爲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
一到得到這個工作路徑是實現to_dict(個體經營):在每個模型輸出字典的方法。然後,您可以在上面的encode_object方法中使用return obj.to_dict()。儘管如此,這仍然讓我覺得很雜亂。 – shawnwall