解析此字符串的最佳方法?

2024-10-02 08:26:23 发布

您现在位置:Python中文网/ 问答频道 /正文

data: {\"id\":123,\"channel\":\"private_A25BHd\",\"text\":{\"content\":\"{\\"m\\":\\"event\\",\\"p\\":{\\"id\\":123123123,\\"aid\\":125123123,\\"sym\\":\\"BITMEX:XBTUSD\\",\\"res\\":\\"1\\",\\"desc\\":\\"test message on line1\\ntest message on line2\\",\\"snd\\":false,\\"snd_file\\":\\"alert\/fired\\",\\"snd_duration\\":0.0,\\"popup\\":true,\\"fire_time\\":123123,\\"bar_time\\":123123,\\"cross_int\\":true}}\",\"channel\":\"alert\"}}

不幸的是,它以字符串的形式出现,不过如果可能的话,我想把它改成dict。你知道吗


Tags: texteventidtruemessagedatatimeon
2条回答

您可以使用函数json.loads(),通过导入json库将字符串解析为JSON对象(Python字典)。你知道吗

代码:

import json

json_string = '{\"id\":123,\"channel\":\"private_A25BHd\",\"text\":{\"content\":\"{\\"m\\":\\"event\\",\\"p\\":{\\"id\\":123123123,\\"aid\\":125123123,\\"sym\\":\\"BITMEX:XBTUSD\\",\\"res\\":\\"1\\",\\"desc\\":\\"test message on line1\\ntest message on line2\\",\\"snd\\":false,\\"snd_file\\":\\"alert\/fired\\",\\"snd_duration\\":0.0,\\"popup\\":true,\\"fire_time\\":123123,\\"bar_time\\":123123,\\"cross_int\\":true}}\",\"channel\":\"alert\"}}'

parsed_string = json.loads(json_string)
print(parsed_string)

输出:

{'text': {'channel': 'alert', 'content': '{"m":"event","p":{"id":123123123,"aid":125123123,"sym":"BITMEX:XBTUSD","res":
"1","desc":"test message on line1\ntest message on line2","snd":false,"snd_file":"alert/fired","snd_duration":0.0,"popu
p":true,"fire_time":123123,"bar_time":123123,"cross_int":true}}'}, 'channel': 'private_A25BHd', 'id': 123}

如果只想打印任何特定值,可以使用

print(parsed_string["id"])

它打印id值,即123

在python中使用json库

import json

json.loads(your_string)

相关问题 更多 >

    热门问题