user7097216
user7097216

Reputation:

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.

Upvotes: 2

Views: 7850

Answers (1)

jcoke
jcoke

Reputation: 1891

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()

Upvotes: 2

Related Questions