不是JSON可序列化的

不是JSON可序列化的

本文介绍了TypeError:ObjectId('')不是JSON可序列化的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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





  TypeError:ObjectId('51948e86c25f4b1d1c0d303c')不是JSON可序列化的
$ b $ p

$ p $ {code $ {'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')不是JSON可串行化

这是RESTfull调用:

  @ appv1.route('/ v1 / analytics')
def get_api_analytics():
# MongoDB中的集合
statistics = sldb.statistics

objectid = ObjectId( 51948e86c25f4b1d1c0d303c)

analytics = statistics.aggregate([
{'$ match':{'owner':objectid}},
{'$ project':{所有者':$ 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} $ b $ $'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$'$' :[$ api_calls_with_key,$ api_calls_without_key]},
'api_calls_per_day':{'$ divide':['$ api_calls_with_key,'$ api_calls_without_key]},{' $ dayOfMonth':datetime.now()}]},
}}
])


print(分析)

返回分析




解决方案

您应该定义您自己的并使用它:

<$ $ b $ import $ b $ import








$ def $ $ b如果isinstance(o,ObjectId):
返回str(o)
返回json.JSONEncoder.default(self,o)

JSONEncoder()。encode(analytics)

也可以按以下方式使用它。

  json.encode(analytics,cls = JSONEncoder)


My response back from MongoDB after querying an aggregated function on document using Python, It returns valid response and i can print it but can not return it.

Error:

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

Print:

{'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}

But When i try to return:

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

It is RESTfull call:

@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 is well connected and collection is there too and I got back valid expected result but when i try to return it gives me Json error. Any idea how to convert the response back into JOSON. Thanks

解决方案

You should define you own JSONEncoder and using it:

import json
from bson import ObjectId

class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        return json.JSONEncoder.default(self, o)

JSONEncoder().encode(analytics)

It's also possible to use it in the following way.

json.encode(analytics, cls=JSONEncoder)

这篇关于TypeError:ObjectId('')不是JSON可序列化的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 20:42