我将来自TCP行的数据作为词典列表。但有时我会一次收到两个数据包。他们看起来像
sdk
我想将其转换为: -
[{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}]
答案 0 :(得分:6)
您可以分两步完成:
][
替换为,
,因为这些连续的方括号代表单独的数据包,加入它们的最简单方法是用逗号替换ast.literal_eval
的字典,即“安全”eval
。import ast
ast.literal_eval(string.replace('][', ','))
[{'property1': 'value1', 'property2': 'value2'},
{'property1': 'value1', 'property2': 'value2'},
{'property1': 'value1', 'property2': 'value2'},
{'property1': 'value1', 'property2': 'value2'},
{'property1': 'value1', 'property2': 'value2'}]
这里假设您将这些“数据包”作为字符串接收。
答案 1 :(得分:1)
输入
l='[{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}]'
使用re
import re
re.findall("\[?([^\]]+)?\]", l)
输出
['{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}',
'{"property1":"value1", "property2":"value2"}',
'{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}'
]