我有一个带有 json 结构的 txt 文件。问题是该文件不仅包含 json 结构,还包含日志错误等原始文本:
2019-01-18 21:00:05.4521|INFO|Technical|Batch Started|
2019-01-18 21:00:08.8740|INFO|Technical|Got Entities List from 20160101 00:00 :
{
"name": "1111",
"results": [{
"filename": "xxxx",
"numberID": "7412"
}, {
"filename": "xgjhh",
"numberID": "E52"
}]
}
2019-01-18 21:00:05.4521|INFO|Technical|Batch Started|
2019-01-18 21:00:08.8740|INFO|Technical|Got Entities List from 20160101 00:00 :
{
"name": "jfkjgjkf",
"results": [{
"filename": "hhhhh",
"numberID": "478962"
}, {
"filename": "jkhgfc",
"number": "12544"
}]
}
我阅读了 .txt 文件,但尝试修补 jason 结构时出现错误: 在 :
import json
with open("data.txt", "r", encoding="utf-8", errors='ignore') as f:
json_data = json.load(f)
输出:json.decoder.JSONDecodeError:额外数据:第 1 行第 5 列(字符 4)
我想parce json并保存为csv文件。
最佳答案
在不假设非 JSON 内容的情况下解析包含 JSON 对象和其他内容的文件的更通用的解决方案是通过大括号将文件内容拆分为片段,从第一个片段开始花括号,然后将其余的片段一一连接,直到连接的字符串可解析为 JSON:
import re
fragments = iter(re.split('([{}])', f.read()))
while True:
try:
while True:
candidate = next(fragments)
if candidate == '{':
break
while True:
candidate += next(fragments)
try:
print(json.loads(candidate))
break
except json.decoder.JSONDecodeError:
pass
except StopIteration:
break
这个输出:
{'name': '1111', 'results': [{'filename': 'xxxx', 'numberID': '7412'}, {'filename': 'xgjhh', 'numberID': 'E52'}]}
{'name': 'jfkjgjkf', 'results': [{'filename': 'hhhhh', 'numberID': '478962'}, {'filename': 'jkhgfc', 'number': '12544'}]}
关于python - 解析包含JSON和文本结构的txt文件中的JSON结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54446387/