【发布时间】:2019-07-17 01:24:52
【问题描述】:
我正在尝试将文件从 mongoDB 读取到本地。
我的代码如下: STRING = "我的本地路径" 路径 = 字符串 + “.json”
with open(PATH,"w") as f:
d = users.find({'Credit' : str("The Associated Press") },
{'article_id':1,'Byline':1} )
for i in d:
f.write(json.dumps(i)+'\n')
f.close()
我收到错误 - “ObjectId”类型的对象不是 JSON 可序列化的。 请提出建议。
【问题讨论】:
-
json不知道如何序列化 pymongo 对象 id 类ObjectId。您可以使用json_util或按照stackoverflow.com/questions/16586180/… 中的建议创建自己的编码器 -
您需要本地副本中的
_id字段吗?如果没有,你可以……。像这样。d = users.find({'Credit' : str("The Associated Press") }, {'article_id': 1,'Byline': 1, '_id': 0} )