首页 > 解决方案 > 如何获取json数据并将其转换为字符串

问题描述

我是 python 中 websockets 和 json 的新手。我只想知道如何将 json 数据转换为字符串,就像这样

{'data': {'id': 26, 'level': 2, 'message': 'Something was Detected'}}

进入

"26"
"2"
"Something was Detected"

或任何格式只是为了使其成为一个字符串。

我正在从本地 websocket 接收我的 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'))

标签: pythonjsonpython-3.x

解决方案


像这样的东西:

data = json.loads(message)
list_of_strings = [str(v) for k, v in data['data'].items()]

推荐阅读