python TypeError:类型builtin_function_or_method的对象不是JSON可序列化的

r1zhe5dt  于 2023-03-21  发布在  Python
关注(0)|答案(1)|浏览(478)

这是我第一次在web服务器上工作,我正在使用flask编写restful get request,将参数传递给我构建的预测模型。

from flask import Flask, Response

app = Flask(__name__)
api = Api(app)

class AST(Resource):
    def get(self):
        args = request.args
        x1 = args['key1']
        x2 = args['key2']
        X = [[x1, x2]]
        x = load_scaler.transform(X)
        y_predict = load_model.predict(x)
        y_predict = load_model.predict(np.array(x)).tolist
        time = [{'predection':y_predict}]
        return Response (json.dumps(time),  mimetype='application/json')

api.add_resource(AST, '/start_time')

if __name__ == '__main__':
    app.run

当我运行代码时,它给了我错误:

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

追踪显示

File "/Users/123/Documents/123/webserver/predictionast.py", line 60, in get
    return Response (json.dumps(time),  mimetype='application/json')
  File "/Users/123/opt/anaconda3/lib/python3.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/Users/123/opt/anaconda3/lib/python3.7/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Users/123/opt/anaconda3/lib/python3.7/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/Users/123/opt/anaconda3/lib/python3.7/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type builtin_function_or_method is not JSON serializable

y_predict是数组

b91juud3

b91juud31#

当你试图将python内置的方法或属性传递给json.loads或dumps方法时,会出现“object of built in types are not JSON serializable”的错误。它无法序列化python方法的内部类型。例如:

json_1 = {"time": datetime.now}
json_2 = {"time": str(datetime.now)}
print(json.loads(json_2))
print(json.loads(json_1))

json_1对象在序列化时尝试打印时会失败,因为它使用了python中的内部bulit方法。另一方面,json_2将被序列化并打印,因为它使用了众所周知的数据类型JSON - String。

相关问题