蟒蛇网络套接字;解析json

Sam*_* M. 5 python websocket

我有这个脚本使用websockets

import asyncio
import websockets
import json

async def echo(websocket, path):
    async for message in websocket:
        print(message)
        await websocket.send(message)

asyncio.get_event_loop().run_until_complete(
    websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()
Run Code Online (Sandbox Code Playgroud)

我从 javascript 发送 json 格式的数据

var socket = new WebSocket('ws://localhost:8765');
socket.send(temp1);
temp1
> {img_width: 600, img_height: 399, areas: Array(1)}
Run Code Online (Sandbox Code Playgroud)

这是 python 打印回来的内容

(pixelart) sam@sam-Lenovo-G51-35:~/code/pixelart$ python path.py
[object Object]
Run Code Online (Sandbox Code Playgroud)

我尝试检查访问其属性的方法,看看是否可以使用print(dir(message))我返回的数据来获取数据

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower','isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Run Code Online (Sandbox Code Playgroud)

看起来更像是字符串的活页夹,所以我尝试检查它的类型print(type(message))

(pixelart) sam@sam-Lenovo-G51-35:~/code/pixelart$ python path.py
<class 'str'>
Run Code Online (Sandbox Code Playgroud)

看起来它将对象转换为字符串。

Jam*_*ott 3

在 JavaScript 中,[object Object]意味着您尝试将未定义如何将自身转换为字符串的对象转换为字符串。

因此,您需要首先使用以下方法将 JSON 对象转换为 JSON 字符串JSON.stringify()

var socket = new WebSocket('ws://localhost:8765');
socket.send(JSON.stringify(temp1);
Run Code Online (Sandbox Code Playgroud)

现在python path.py应该打印您发送的 JSON 字符串。

要将 Python 端的 JSON 字符串转换为字典(以便您可以在本机使用它),您可以使用json.loads(string)(loads 意思字符串加载)。