2

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.

user2510479
  • 1,528
  • 13
  • 17
  • `json` doesn't know how to serialize pymongo object id class `ObjectId`. You can use `json_util` or create your own encoder as suggested in https://stackoverflow.com/questions/16586180/typeerror-objectid-is-not-json-serializable – Yohanes Gultom Feb 23 '19 at 02:25
  • Possible duplicate of [TypeError: ObjectId('') is not JSON serializable](https://stackoverflow.com/questions/16586180/typeerror-objectid-is-not-json-serializable) – Yohanes Gultom Feb 23 '19 at 02:38
  • 1
    Do you need the `_id` field in your local copy? If not you could sth. like this. `d = users.find({'Credit' : str("The Associated Press") }, {'article_id': 1,'Byline': 1, '_id': 0} )` – b00r00x0 Feb 27 '19 at 17:40

1 Answers1

2

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()
jcoke
  • 1,555
  • 1
  • 13
  • 27