我是python中的websockets和json的新手。我只想知道如何像这样将json数据转换为字符串
{'data': {'id': 26, 'level': 2, 'message': 'Something was Detected'}}
进入
"26"
"2"
"Something was Detected"
或仅将其制成字符串的任何格式。
我正在从本地网络套接字接收我的json数据,此处是代码。
async with websockets.connect(url) as websocket:
data = dict(topic='device:10', event="phx_join", payload={}, ref=0)
await websocket.send(json.dumps(data))
# Json data will be receive here
message = await websocket.recv()
# then it will be printed here
print(message)
# I need to convert the message into string
asyncio.get_event_loop().run_until_complete(hello('ws://localhost:4000/socket/websocket'))
答案 0 :(得分:0)
类似这样的东西:
data = json.loads(message)
list_of_strings = [str(v) for k, v in data['data'].items()]
答案 1 :(得分:0)
这是我获得所需输出的方式
async with websockets.connect(url) as websocket:
data = dict(topic='device:10', event="phx_join", payload={}, ref=0)
await websocket.send(json.dumps(data))
# Json data will be receive here
message = await websocket.recv()
# then it will be printed here
print(message)
# The answer for the question
message_json = json.loads(message)
id = message_json['data']['id']
print(id)
level = message_json['data']['level']
print(level)
mes = message_json['data']['message']
print(mes)
asyncio.get_event_loop().run_until_complete(hello('ws://localhost:4000/socket/websocket')