如何使用 python http server/client 发送字典

How to send a dictionary with python http server/client

我正在使用库 http.server 和 http.client 来构建 server/client 结构。服务器一直在线,客户端发出请求。

调用服务器时,它会调用一个 returns 字典的抓取工具,目前我是这样发送的:

self.wfile.write(str(dictionary).encode("utf-8"))

但是客户端收到一个我必须解析的字符串。服务器是否可以发送字典? (或者更好,json)

您应该尝试使用 json.dumps({"a": 1, "b": 2}) 并发送您的 JSON 对象而不是将其编码为 utf-8。