使用 Python 的 Flask 和 jsonpickle 在 JSON 中获取不需要的转义字符

Getting unwanted escape character in JSON using Python's Flask and jsonpickle

from flask import Flask, request, abort
from flask_restful import Api, Resource
import jsonpickle

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

user_dict = {}
user_id = 0

class User(Resource):
    @staticmethod
    def get(path_user_id):
        if path_user_id not in user_dict:
            abort(400)

        test = jsonpickle.encode(user_dict.get(path_user_id), unpicklable=False)

        return jsonpickle.encode(user_dict.get(path_user_id), unpicklable=False)

    @staticmethod
    def put(path_user_id):
        if path_user_id not in user_dict:
            abort(400)

        update_and_add_user_helper(path_user_id, request.get_json())

    @staticmethod
    def delete(path_user_id):
        if path_user_id not in user_dict:
            abort(400)

        user_dict.pop(path_user_id, None)


class UserList(Resource):
    @staticmethod
    def get():
        return jsonpickle.encode(user_dict, unpicklable=False)

    @staticmethod
    def post():
        global user_id
        user_id = user_id + 1
        update_and_add_user_helper(user_id, request.get_json())


def update_and_add_user_helper(u_id, request_payload):
    name = request_payload["name"]
    age = request_payload["age"]
    address = request_payload["address"]
    city = request_payload["city"]
    state = request_payload["state"]
    zip_code = request_payload["zip"]
    user_dict[u_id] = Person(name, age, address, city, state, zip_code)


class Person:
    def __init__(self, name, age, address, city, state, zip_code):
        self.name = name
        self.age = age
        self.address = address
        self.city = city
        self.state = state
        self.zip_code = zip_code

api.add_resource(User, "/users/<int:path_user_id>")
api.add_resource(UserList, "/users")

if __name__ == "__main__":
    app.run(debug=True)

调试 get 方法(通过用户 id)后,我得到了这个

test = '{"address": "123 Chestnut Ln", "age": 35, "city": "Denton", "name": "James Smith", "state": "Texas", "zip_code": "76210"}'

但是显示的响应是:"{\"1\": {\"address\": \"123 Chestnut Ln\", \"age\": 35, \"city\": \"Denton\", \"name\": \"James Smith\", \"state\": \"Texas\", \"zip_code\": \"76210\"}}"

Flask 是否在返回时序列化对象?

此外,请假设已完成 POST 请求并且字典中有值。

我尝试搜索 flask 文档,但没有成功,所以我尝试 fiddle 使用您的代码,所以这是我找到的内容:

当我改变时:

return jsonpickle.encode(user_dict.get(path_user_id), unpicklable=False)

return user_dict.get(path_user_id)

我遇到了 TypeError: Object of type 'Person' is not JSON serializable 异常。看来flask毕竟是序列化响应的。