简体   繁体   中英

mongoDB Object of type 'ObjectId' is not JSON serializable

I am trying to read file from mongoDB to local.

My code are as below: STRING = "myLocalPath" PATH = 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()

I am getting Error - Object of type 'ObjectId' is not JSON serializable.. please suggest.

Try this:

from bson import json_util
 for i in d:
        f.write(json.dumps(i, default = json_util.default)+'\n')
        f.close()

OR

import json
 for i in d:
        f.write(json.dumps(i, default = str)+'\n')
        f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM