我正在解析包含json对象的文件。问题是某些文件在一行中有多个对象。例如:
{"data1": {"data1_inside": "bla{bl\"a"}}{"data1": {"data1_inside": "blabla["}}{"data1": {"data1_inside": "bla{bla"}}{"data1": {"data1_inside": "bla["}}
我做了一个函数,尝试在没有左括号的情况下解析子字符串,但是值中可能有大括号。我尝试过通过检查引号的开头和结尾来跳过值,但是也有带有转义引号的值。有关如何处理此问题的任何想法?
我的尝试:
def get_lines(data): lines = [] open_brackets = 0 start = 0 is_comment = False for index, c in enumerate(data): if c == '"': is_comment = not is_comment elif not is_comment: if c == '{': if not open_brackets: start = index open_brackets += 1 if c == '}': open_brackets -= 1 if not open_brackets: lines.append(data[start: index+1]) return lines
简单但不够健壮的版本:
>>> import re >>> s = r'{"data1": {"data1_inside": "bla{bl\"a"}}{"data1": {"data1_inside": "blabla["}}{"data1": {"data1_inside": "bla{bla"}}{"data1": {"data1_inside": "bla["}}' >>> r = re.split('(\{.*?\})(?= *\{)', s) ['', '{"data1": {"data1_inside": "bla{bl\\"a"}}', '', '{"data1": {"data1_inside": "blabla["}}', '', '{"data1": {"data1_inside": "bla{bla"}}', '{"data1": {"data1_inside": "bla["}}']
如果}{包含在字符串中,则将失败
}{
正如其他建议一样,您然后可以尝试解析每个元素。如果无效,则应与下一个元素一起检查此元素。
请注意,这r是上面代码的结果
r
accumulator = '' res = [] for subs in r: accumulator += subs try: res.append(json.loads(accumulator)) accumulator = '' except: pass