使用 Python tokenize module 将文本流转换为带有逗号而不是分号的文本流。 Python 标记器也很乐意处理 JSON 输入,甚至包括分号。标记器将字符串显示为 整个标记,而“原始”分号在流中作为单个 token.OP 标记供您替换:
import tokenize
import json
corrected = []
with open('semi.json', 'r') as semi:
for token in tokenize.generate_tokens(semi.readline):
if token[0] == tokenize.OP and token[1] == ';':
corrected.append(',')
else:
corrected.append(token[1])
data = json.loads(''.join(corrected))
这假设一旦您将分号替换为逗号,格式变为有效的 JSON;例如在结束 ] 或 } 之前不允许使用尾随逗号,但如果下一个非换行符是右大括号,您甚至可以跟踪添加的最后一个逗号并再次删除它。
演示:
>>> import tokenize
>>> import json
>>> open('semi.json', 'w').write('''\
... {
... "client" : "someone";
... "server" : ["s1"; "s2"];
... "timestamp" : 1000000;
... "content" : "hello; world"
... }
... ''')
>>> corrected = []
>>> with open('semi.json', 'r') as semi:
... for token in tokenize.generate_tokens(semi.readline):
... if token[0] == tokenize.OP and token[1] == ';':
... corrected.append(',')
... else:
... corrected.append(token[1])
...
>>> print ''.join(corrected)
{
"client":"someone",
"server":["s1","s2"],
"timestamp":1000000,
"content":"hello; world"
}
>>> json.loads(''.join(corrected))
{u'content': u'hello; world', u'timestamp': 1000000, u'client': u'someone', u'server': [u's1', u's2']}
令牌间空白已被删除,但可以通过注意 tokenize.NL 令牌以及作为每个令牌一部分的 (lineno, start) 和 (lineno, end) 位置元组来重新设置。由于标记周围的空格对 JSON 解析器来说无关紧要,因此我没有为此烦恼。