【问题标题】:Object of type 'ObjectID' is not JSON serializable“ObjectID”类型的对象不是 JSON 可序列化的
【发布时间】:2018-01-18 19:54:28
【问题描述】:

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

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

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

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

类联系人(资源):

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 对象进行双重编码来清除可序列化的错误。对于我正在做的事情,这似乎不是一个好的解决方案。

【问题讨论】:

  • 我试过这个,它没有产生预期的结果 - 我不记得这个解决方案到底做了什么,但我的暂存空间中仍然有代码并标记为不是解决方案。

标签: python-3.x pymongo flask-restful


【解决方案1】:

我认为这对你会有帮助。

from flask import Response
...
...
list_of_books = mongo_db.db[BOOK_COLLECTION].find()
list_of_books = [each_book for each_book in list_of_books]

return  Response(json.dumps(list_of_books,default=str),mimetype="application/json")

【讨论】:

    【解决方案2】:
    from bson import json_util
    items = mongo.db.shop_items.find_one({"item_name": "abc"})
    return make_response(json_util.dumps({"items": items}), HTTPStatus.OK)
    

    ---这解决了我的错误。

    【讨论】:

      【解决方案3】:

      看起来一个简单的解决方案是将 _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

      【讨论】:

        猜你喜欢
        • 2019-07-17
        • 1970-01-01
        • 1970-01-01
        • 2021-03-11
        • 2021-07-04
        • 2021-12-10
        • 1970-01-01
        • 2021-09-27
        • 2019-09-04
        相关资源
        最近更新 更多