使用 python 在损坏的 json 中解析问题

parsing issues in corrupted json using python

我有一个损坏的 json,如下所示:

{'a': 'b', 'c': "abcd'efgh ijklm"}

在使用 python json.loads 之前,我需要做两件事:

  1. 将双引号内的单引号替换为\'
  2. 用双引号
  3. 替换所有其他单引号,\'除外

我不确定如何执行这两个步骤。请帮忙。

实际上你不能使用json.loads function to deserialize your string because the string doesn't contain a valid JSON document. Instead, you should consider to use the ast.literal_eval功能。

演示:

In [25]: import ast

In [26]: with open('inputfile') as f:
   ....:     for d in map(ast.literal_eval, f):
   ....:         print(d)
   ....:         
{'c': "abcd'efgh ijklm", 'a': 'b'}
{'c': "abcdgfgfgg", 'a': 'b'}