Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在python中解析来自套接字的JSON(不是嵌套JSON)对象_Python_Json_Sockets - Fatal编程技术网

无法在python中解析来自套接字的JSON(不是嵌套JSON)对象

无法在python中解析来自套接字的JSON(不是嵌套JSON)对象,python,json,sockets,Python,Json,Sockets,在python中,我从服务器读取JSON对象,JSON对象的大小是不固定的。我根据socket.recv(1024)中给定的缓冲区大小从服务器获取数据。如何检查从服务器套接字接收的JSON对象是否已满/已完成,因为在解析该JSON时,我遇到了一个错误。 请注意,我的JSON对象不是嵌套的 ****示例代码**** def get_data(): s = socket.socket() host = 'IP_Address' port = 'Port_Number'

在python中,我从服务器读取JSON对象,JSON对象的大小是不固定的。我根据socket.recv(1024)中给定的缓冲区大小从服务器获取数据。如何检查从服务器套接字接收的JSON对象是否已满/已完成,因为在解析该JSON时,我遇到了一个错误。 请注意,我的JSON对象不是嵌套的

****示例代码****

def get_data():
    s = socket.socket()
    host = 'IP_Address'
    port = 'Port_Number'

    # connection to hostname on the port.
    s.connect((host, port))
    msg=''
    while(True):        
        msg = s.recv(1024)
        print(msg.decode('ascii'))   
        jsonObject=json.loads(msg.decode('ascii'))     

    s.close()    
下面是错误

Traceback (most recent call last):

  File "d:/xxxxxxxxxxxxx/Python_Test.py", line 26, in <module>
    get_data()

  File "d:/xxxxxxxxxxxxx/Python_Test.py", line 20, in get_data
    temp=json.loads(msg.decode('ascii'))

  File "xxxxxxxxxxxxx\Python\Python37\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)

  File "xxxxxxxxxxxxx\Python\Python37\lib\json\decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 777)
回溯(最近一次呼叫最后一次):
文件“d:/xxxxxxxxxxxx/Python_Test.py”,第26行,在
获取_数据()
get\U数据中第20行的文件“d:/xxxxxxxxxxxx/Python\u Test.py”
temp=json.load(msg.decode('ascii'))
文件“xxxxxxxxx\Python\Python37\lib\json\\uuuuu init\uuuuuu.py”,第348行,加载
返回\u默认\u解码器。解码
文件“xxxxxxxx\Python\Python37\lib\json\decoder.py”,第340行,解码
raise JSONDecodeError(“额外数据”,s,结束)
json.decoder.JSONDecodeError:额外数据:第2行第1列(char 777)

在每个循环中接收1024字节,如果json对象大于1024字节,则必须处理未完成的json字符串。
此外,您可能有两个1024字节甚至更多的json对象。您可以将代码更改为下面的代码

def get_data():
    s = socket.socket()
    host = 'IP_Address'
    port = 'Port_Number'
    s.connect((host, port))
    msg=''
    while True:        
        r = s.recv(1024)
        msg += r.decode('ascii')
        while True:
            start = msg.find("{")
            end = msg.find("}") 
            if start==-1 or end==-1:   # if can not find both { and } in string  
                break
            jsonObject=json.loads(msg[start:end+1])  # only read { ... } and not another uncompleted data
            #  do whatever you want with jsonObject here
            msg = msg[end+1:]
    s.close()  

注意:只有当您的数据中没有任何嵌套的json时,此代码才能正常工作(如:
{“device\u id”:{“other\u json”:“something”}

您需要等待收到完整的json,然后对其进行解析,类似的操作应该可以:

msg = ''
while(True):        
    response = s.recv(1024)
    if not response:
        break
    msg += response
jsonObject=json.loads(msg.decode('ascii'))     

请告诉我们您代码中的
msg
(在出现错误的行之前打印)我认为
msg
有多个JSON对象。您可以打印收到的内容。你能在这里分享一下吗?这样我们就可以更好地了解发生了什么事。我删除了注释:)可能是因为每个循环只接收1024字节,json的大小大于that@shotgunner下面是消息。{“divice_id”:“37843”,“slot”:“2019-03-13 11:49:58.255”,“1”:“237.51”,“2”:“240.79”,“3”:“241.48”,“4”:“10.28”,“62”:“383.0”}{“divice_id”:“33295”,“slot”:“2019-03-13 11:49:58.33”,“1”:"238.88","2":"240.71","3":"241.05","4":"165.9","5":"187.63","6":"162.47","7":“3630谢谢您的回复,当我试图执行您的代码时,我得到了下面的错误UnboundLocalError:赋值前引用的局部变量'r'。那么我应该在何处声明r在while循环内部还是在while循环外部?当我声明r=''在msg=''下面和while循环上面时,我得到了下面的错误r+=s.recv(1024)TypeError:只能将str(而不是“字节”)连接到str@Amit这是
r+=
中的一个类型,我现在修复代码,检查它。非常感谢。我得到了所需的输出。嗨,安基特,如果我在同一个消息中收到两个JSON obj,会怎么样。@Amit在这种情况下
JSON.JSONDecoder.raw_decode
是正确的方法。看到了吗