修复格式错误的字符串?

时间:2017-10-30 06:28:33

标签: python string

我将来自TCP行的数据作为词典列表。但有时我会一次收到两个数据包。他们看起来像

sdk

我想将其转换为: -

[{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}][{"property1":"value1", "property2":"value2"}, {"property1":"value1", "property2":"value2"}]

2 个答案:

答案 0 :(得分:6)

您可以分两步完成:

  1. ][替换为,,因为这些连续的方括号代表单独的数据包,加入它们的最简单方法是用逗号替换
  2. 将字符串转换为包含ast.literal_eval的字典,即“安全”eval
  3. 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"}'
]