Flask TypeError '不是 JSON 可序列化的' - 嵌套字典

Raf*_*ues 6 json flask notserializableexception

我使用 Flask 作为我服务器的框架,在返回响应时出现以下错误:

> Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Python27\lib\site-packages\flask_restful\__init__.py", line 480, in wrapper
    resp = resource(*args, **kwargs)
  File "C:\Python27\lib\site-packages\flask\views.py", line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File "C:\Python27\lib\site-packages\flask_restful\__init__.py", line 595, in dispatch_request
    resp = meth(*args, **kwargs)
  File "rest.py", line 27, in get
    return jsonify(**solution)
  File "C:\Python27\lib\site-packages\flask\json.py", line 263, in jsonify
    (dumps(data, indent=indent, separators=separators), '\n'),
  File "C:\Python27\lib\site-packages\flask\json.py", line 123, in dumps
    rv = _json.dumps(obj, **kwargs)
  File "C:\Python27\lib\json\__init__.py", line 251, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "C:\Python27\lib\json\encoder.py", line 209, in encode
    chunks = list(chunks)
  File "C:\Python27\lib\json\encoder.py", line 434, in _iterencode
    for chunk in _iterencode_dict(o, _current_indent_level):
  File "C:\Python27\lib\json\encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "C:\Python27\lib\json\encoder.py", line 332, in _iterencode_list
    for chunk in chunks:
  File "C:\Python27\lib\json\encoder.py", line 332, in _iterencode_list
    for chunk in chunks:
  File "C:\Python27\lib\json\encoder.py", line 442, in _iterencode
    o = _default(o)
  File "C:\Python27\lib\site-packages\flask\json.py", line 80, in default
    return _json.JSONEncoder.default(self, o)
  File "C:\Python27\lib\json\encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: {'origin': u'porto', 'dest': u'lisboa', 'price': '31', 'date': '2017-12-23', 'url': u'https://www.google.pt/flights/#search;f=opo;t=lis;d=2017-12-23;r=2017-12-24'} is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

我有以下功能:

from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from flask_cors import CORS, cross_origin
from json import dumps
import flights
import solveProblem

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

class Flights(Resource):
    def get(self, data):
        print 'received data from client: ' + data
        solution = solveProblem.solve(data)
        print 'got the solution from the script! \nSOLUTION: \n'
        print solution
        return jsonify(solution)

api.add_resource(Flights, '/flights/<string:data>')

if __name__ == '__main__':
    app.run()
Run Code Online (Sandbox Code Playgroud)

在调试问题时,我发现以下解决方案不起作用:

1) 返回解决方案而不是 {'solution': solution}

2)做jsonify(解决方案)

3)做jsonify(**解决方案)

以上都不适合我;我想知道为什么会发生这种情况,当我试图返回一个有效的字典时:

{'flights': [[{'origin': u'porto', 'dest': u'lisboa', 'price': '31', 'date': '2017-12-23', 'url': u'https://www.google.pt/flights/#search;f=opo;t=lis;d=2017-12-23;r=2017-12-24'}]], 'cost': '31'}
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。谢谢

小智 7

我的猜测是,当您创建“解决方案”时,分配给它的数据是格式不正确的字典

    {'item', 'value'}
Run Code Online (Sandbox Code Playgroud)

代替:

    {'item': 'value'}
Run Code Online (Sandbox Code Playgroud)

因此创建一个集合而不是字典


Raf*_*ues -2

据我发现,当响应不是纯 python 字典时,通常会发生此错误。这发生在我身上,因为我试图传递一个类对象。因此,为了解决这个问题,我创建了一个类方法,它返回一个描述对象的字典,并使用它来创建 json 响应。

结论:使用纯Python对象,它很容易转换为JSON。