python WebSocket;解析json

python WebSocket;解析json,python,websocket,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

我使用
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()
我从json格式的javascript发送数据

var socket = new WebSocket('ws://localhost:8765');
socket.send(temp1);
temp1
> {img_width: 600, img_height: 399, areas: Array(1)}
这是python打印的内容

(pixelart) sam@sam-Lenovo-G51-35:~/code/pixelart$ python path.py
[object Object]
我试图检查访问其属性的方法,看看是否可以使用
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']
看起来更像字符串的活页夹,所以我尝试检查它的类型
print(type(message))

(像素艺术)sam@sam-Lenovo-G51-35:~/code/pixelart$python path.py

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

在JavaScript中,
[object object]
表示您试图将一个对象转换为字符串,但该对象没有定义如何将自身转换为字符串

因此,首先需要使用
JSON.stringify()
,将JSON对象转换为JSON字符串:

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

要将Python端的JSON字符串转换为dict(因此您可以在本地使用它),可以使用
JSON.loads(string)
(loads的意思是loadfromstring)

(pixelart) sam@sam-Lenovo-G51-35:~/code/pixelart$ python path.py
<class 'str'>
var socket = new WebSocket('ws://localhost:8765');
socket.send(JSON.stringify(temp1);