如何在Python中将拼接式JSON字节串解析为字典列表?
问题描述
收到客户端发来的字节数据:
b'{"time": 1234.23432, "message": "Printer1"}{"time": 63743.4332, "message": "Printer2"}{"time": 82374.43253, "message": "Printer3"}'
需要解析成字典列表:
[{"time": 1234.23432, "message": "Printer1"}, {"time": 63743.4332, "message": "Printer2"}, {"time": 82374.43253, "message": "Printer3"}]
直接使用json.loads(data.decode("utf-8"))报错,原因是输入的是JSON Lines格式(多个独立JSON对象直接拼接),而非标准的JSON数组结构。
解决方案
方法1:用JSONDecoder的raw_decode逐个解析
json.JSONDecoder的raw_decode方法可以从字符串中解析出第一个JSON对象,同时返回剩余未解析的字符串,循环调用即可处理所有对象:
import json data = b'{"time": 1234.23432, "message": "Printer1"}{"time": 63743.4332, "message": "Printer2"}{"time": 82374.43253, "message": "Printer3"}' decoded_str = data.decode("utf-8") decoder = json.JSONDecoder() result = [] remaining_str = decoded_str while remaining_str.strip(): obj, idx = decoder.raw_decode(remaining_str) result.append(obj) remaining_str = remaining_str[idx:] print(result)
这个方法更健壮,能处理JSON对象内部包含}{字符的极端情况。
方法2:转换为标准JSON数组格式
如果可以确定输入的JSON对象中不会出现}{组合,可以直接修改字符串格式,再用json.loads解析:
import json data = b'{"time": 1234.23432, "message": "Printer1"}{"time": 63743.4332, "message": "Printer2"}{"time": 82374.43253, "message": "Printer3"}' decoded_str = data.decode("utf-8") # 包裹成数组结构,替换对象间的分隔符 formatted_str = f"[{decoded_str.replace('}{', '}, {')}]" result = json.loads(formatted_str) print(result)
这个方法实现简单,适合场景明确的业务需求。
内容的提问来源于stack exchange,提问作者user2880575
相关产品推荐
相关产品推荐

