python - 类型错误 : ObjectId ('' ) is not JSON seriali

我在使用 Python 查询文档上的聚合函数后从 MongoDB 返回的响应,它返回有效响应,我可以打印它但不能返回它。

错误:

TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable

打印:

{'result': [{'_id': ObjectId('51948e86c25f4b1d1c0d303c'), 'api_calls_with_key': 4, 'api_calls_per_day': 0.375, 'api_calls_total': 6, 'api_calls_without_key': 2}], 'ok': 1.0}

但是当我尝试返回时:

TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable

是 RESTfull 调用:

@appv1.route('/v1/analytics')
def get_api_analytics():
    # get handle to collections in MongoDB
    statistics = sldb.statistics

    objectid = ObjectId("51948e86c25f4b1d1c0d303c")

    analytics = statistics.aggregate([
    {'$match': {'owner': objectid}},
    {'$project': {'owner': "$owner",
    'api_calls_with_key': {'$cond': [{'$eq': ["$apikey", None]}, 0, 1]},
    'api_calls_without_key': {'$cond': [{'$ne': ["$apikey", None]}, 0, 1]}
    }},
    {'$group': {'_id': "$owner",
    'api_calls_with_key': {'$sum': "$api_calls_with_key"},
    'api_calls_without_key': {'$sum': "$api_calls_without_key"}
    }},
    {'$project': {'api_calls_with_key': "$api_calls_with_key",
    'api_calls_without_key': "$api_calls_without_key",
    'api_calls_total': {'$add': ["$api_calls_with_key", "$api_calls_without_key"]},
    'api_calls_per_day': {'$divide': [{'$add': ["$api_calls_with_key", "$api_calls_without_key"]}, {'$dayOfMonth': datetime.now()}]},
    }}
    ])


    print(analytics)

    return analytics

db 连接良好,收集也在那里,我得到了有效的预期结果,但是当我尝试返回时,它给了我 Json 错误。知道如何将响应转换回 JSON。谢谢

最佳答案

Pymongo提供json_util - 你可以使用它来处理 BSON 类型

def parse_json(data):
    return json.loads(json_util.dumps(data))

关于python - 类型错误 : ObjectId ('' ) is not JSON serializable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16586180/

相关文章:

javascript - 在NodeJS中获取Mongo数据库中插入文档的_id

macos - 无法连接到mongodb errno :61 Connection refused

mongodb - 未指定排序顺序时,MongoDB 如何对记录进行排序?

MongoDB GPG - 无效签名

node.js - 如何获得 Mongoose 模型的所有计数?

mongodb - 为什么 Mongoose 既有模式又有模型?

mongodb - GridFS 对于生产来说是否足够快速和可靠?

node.js - ( Node :3341) DeprecationWarning: Mongoo

mongodb - Mongoose 的 $or 条件的 find 方法无法正常工作

linux - 无法连接到服务器 127.0.0.1 shell/mongo.js