簡體   English   中英

python websockets; 解析json

[英]python websockets; parse json

我有這個使用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))

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

看起來它將對象轉換為字符串。

在 JavaScript 中, [object Object]表示您嘗試將一個對象轉換為未定義如何將自身轉換為字符串的對象。

因此,您需要首先使用JSON.stringify()將 JSON 對象轉換為 JSON 字符串:

var socket = new WebSocket('ws://localhost:8765');
socket.send(JSON.stringify(temp1);

現在python path.py應該打印你發送的 JSON 字符串。

要在事物的Python一側JSON字符串轉換為一個字典(這樣你就可以本地使用它),你可以使用json.loads(string) (負載意味着從s特林負荷)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM