python-3.x - 类型 'ObjectID'的对象不可JSON序列化

标签 python-3.x pymongo flask-restful

我遇到了一个似乎很常见的问题,但到目前为止,我还没有找到适用于我的解决方案。我想我只是想念一些小东西,但是我很想寻求帮助。我正在尝试使用flask和pymongo获取json输出。

这是控制台中使用print(results)的对象:

[{'_id': ObjectId('598b5de38161a821188f1a7c'), 'first name': 'first name', 'last Name': 'last name'}]

当我尝试返回该错误时:
TypeError:“ObjectId”类型的对象不可JSON序列化

类Contacts(资源):
def get(self):
    results =[]
    connect = MongoClient("<REMOVED>")
    db = connect['<REMOVED>']
    collection = db['contact']
    contacts = collection.find()

    if collection:
        number_of_contacts = collection.count()
        for document in contacts:
            results.append(document)
        print(results)
        return {'results': results, 'count': number_of_contacts}

我尝试了bson.json_util建议。它确实通过对我的json对象进行了双重编码来清除可序列化的错误。似乎对于我正在做的事情来说,这不是一个好的解决方案。

最佳答案

看起来一个简单的解决方案是将_id转换为适合我们尝试执行的字符串。

for document in contacts:
    document['_id'] = str(document['_id'])
    results.append(document)

找到解决方案,读取Getting 'TypeError: ObjectId('') is not JSON serializable' when using Flask 0.10.1

关于python-3.x - 类型 'ObjectID'的对象不可JSON序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45615855/

相关文章:

python - 仅在 pandas 数据框中查找字符串并用数字替换字符串

python - pymongo : delete records elegantly

python - 使用示例代码时出现 Pymongo pymongo.errors.ServerSelectionTimeoutError

mongodb - 客户端退出后 Pymongo 放弃 "pymongo_kill_cursors_thread"

python - 如何在 Flask-restful 中返回错误消息?

python - 如何在删除列表中单词之间的连字符时克服不一致

python-3.x - 如何从 gensim 上的 w2v 获取 tf-id

html - 如何隐藏 pandas <1.4 中的索引级别

python - Flask-restful API 不接受 json

python - 如何发送用户名 :password to unittest's app. get() 请求?