TypeError:类型X的对象不可JSON序列化

时间:2018-10-23 01:51:10

标签: python json flask

我该如何返回一个包含对象数组的正确字典? 我正在制作Flask API,但没有得到很好的结果,以后可以将其用作json对象。

这是输出以及我的输出方式 输出:

{
    "starttime": "2018-10-19 12:10:00",
    "endtime": "2018-10-19 12:11:00",
    "env": "TEST",
    "statistics": "{\"TEST\": {\"queryUsers\": {\"calls\": 43, \"avgtime\": 1, \"errors\": 0, \"first_error\": null, \"last_error\": null, \"timeouts\": 0, \"first_to\": null, \"last_to\": null},
...

路由器:

def get(self, env):
if env == 'TEST':
    start = "2018-10-19 12:10:00"
    end = "2018-10-19 12:11:00"
    stats = self.scontroller.getStatistics(start, end, 'ALL')

    return {'starttime': start, 'endtime': end, 'env': env, 'statistics': json.dumps(stats, cls=MyJSONEncoder)}, 200

return "ENV not found", 404

如果我尝试返回此值

return {'starttime': start, 'endtime': end, 'env': env, 'statistics': stats}, 200

我会得到:

    raise TypeError(f'Object of type {o.__class__.__name__} '
    TypeError: Object of type Statistic is not JSON serializable

我的json编码器:

class MyJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Metric):
            pass
        if isinstance(obj, Statistic):
            return vars(obj)

        return JSONEncoder.default(self, obj)

应在统计信息中使用的格遵循以下模型:

{
  "ENVNAME":{
            "APINAME":{
                           <Object Statistic>,
                           <Object Statistic>,
                           <Object Statistic>,
                           <Object Statistic>
                       },
            "ANOTHERAPI": {...}
           }
}

它是这样安装的:

Statistic.py

class Statistic():

def __init__(self, calls, avgtime, errors, first_error, last_error, timeouts, first_to, last_to):
    self.calls = calls
    self.avgtime = avgtime
    self.errors = errors
    self.first_error = first_error
    self.last_error = last_error
    self.timeouts = timeouts
    self.first_to = first_to
    self.last_to = last_to

在控制器上:

stats[env][api] = Statistic(calls, avgtime, errors, first_er, last_er, tos, first_to, last_to)

感谢您的帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

通过在应用启动器中使用flask.jsonify()并声明app.json_encoder = MyJSONEncoder进行修复。

        response = jsonify(starttime=start, endtime=end, env=env, statistics=stats)
        response.status_code = 200
        return response

希望它对其他人也有帮助。