简体   繁体   English

使用Python从套接字解析JSON消息

[英]Parse JSON message from socket using Python

I'm just looking for a really good hint on solving my problem, not necessarily the complete solution. 我只是在寻找有关解决我的问题的很好的提示,不一定是完整的解决方案。

I can receive the following string over a TCP socket: 我可以通过TCP套接字接收以下字符串:

{"id":"555","jsonrpc":"2.0","result":null,"timestamp":"2018-08-03T17:32:41.894"}

this is how I'm reading in the data 这就是我读取数据的方式

while True:
    data = sock.recv(1024).decode('utf-8')
    if not data:
        sys.exit(0)

I'm trying to parse elements using the following method: 我正在尝试使用以下方法解析元素:

if (data["id"] == "555"):
    print("found it..now call a function!")

No matter what I try I get the following TypeError: string indices must be integers 无论我尝试什么,都会收到以下TypeError:字符串索引必须为整数

I'm using Python version 3.7. 我正在使用Python版本3.7。 I'm new to Python and programming for that matter and I've been at this for days. 我是Python和编程方面的新手,而且我已经工作了几天。

Thanks in advance! 提前致谢!

Python has a built-in json library specifically for this kind of thing. Python有专门用于这种事情的内置json库。

import json
...
data = sock.recv(1024).decode('utf-8')    # this returns a JSON-formatted String
parsed_data = json.loads(data)            # this turns the string into a python dict
if parsed_data['id'] == '555':            # because it is now a dictionary, this will work
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM