Python3:在字节数组中查找多个JSON对象

问题描述 投票:0回答:2

我有各种大小的字节数组通过串行端口传入,必须将其转换为JSON对象。

问题

问题是,可能同时出现多封邮件。当我解码数组时,数据看起来像这样:

{"time":1571813129,"device":"abc","count":0}{"time":1571813129,"device":"def","count":0}

其中多个字符串在一起,我试图以一种简单的方式将它们分开,然后转换为JSON。

代码

x = ser1.read(256)
if x:
    x = x.decode()

我也尝试过ser1.readline(),但是数据仍然在同一行上,所以我又回到了同样的问题。

问题

处理这种情况的最佳方法是什么?

  • 字符串的长度不同(我把read(256)放得足够多了]
  • 同时有多条消息(当前为字符串,但我想拆分为单个JSON对象)
json python-3.x pyserial
2个回答
0
投票

您可以将片段收集到字符串中,并在其中查找}{进行操作

buf=''
while True:
  frag=ser1.read(256)
  buf.append(frag.decode()) # perhaps with that if, I do not know the API
  try
    i=buf.find('}{')
    while i>=0:
      msg=json.loads(buf[:i+1])
      use(msg)
      buf=buf[i+1:]
      i=buf.find('}{')

0
投票

发布问题后,我继续在字符串中找到}。然后在位置上循环-将它们用作切片的起点和终点。不漂亮,但是可以用。

def find_char(data, c):
    return [pos for pos, char in enumerate(data) if char == c]


def find_objects(data):
    json_objects = []
    # Find the '}'
    pos_list = find_char(data, '}')
    # Loop over positions of }
    for x in pos_list:
        p = pos_list.index(x)
        # If the first object
        if p == 0:
            start = 0
            end = x + 1
        else:
            # For multiple objects
            if len(data) == x:
                # If the last object
                end = x
            else:
                # If in the middle of the string
                end = x + 1
            start = pos_list[p - 1] + 1
        json_objects.append(data[start:end])
    return json_objects
© www.soinside.com 2019 - 2024. All rights reserved.