python websocket client send json

在 Python 中使用 websocket 客户端发送 JSON 数据,需要先安装 websocket-client 库,然后使用如下代码:

import json
import websocket
# 建立 websocket 连接
ws = websocket.create_connection("ws://echo.websocket.org")
# 准备要发送的 JSON 数据
data = {
    "key1": "value1",
    "key2": "value2"
# 将 JSON 数据编码成字符串
json_data = json.dumps(data)
# 使用 send() 方法发送数据
ws.send(json_data)
# 关闭 websocket 连接
ws.close()

在这段代码中,我们使用了 json 库的 dumps() 方法将 Python 字典类型的数据转换成 JSON 格式的字符串,然后使用 websocket 库的 send() 方法将这个字符串发送出去。

希望这对你有帮助。

  •