在Python中解析不带引号的Json

Ank*_*ngh 5 python json python-2.7 python-3.x jsonparser

我正在尝试将 JSON 输入解析为 Python 中的字符串,但无法解析为列表或字典,因为 JSON 输入的格式不正确(由于中间件的限制,这里不能做太多事情。)

{
  "Records": "{Output=[{_fields=[{Entity=ABC  , No=12345, LineNo=       1, EffDate=20200630}, {Entity=ABC  , No=567, LineNo=       1, EffDate=20200630}]}"
}
Run Code Online (Sandbox Code Playgroud)

我试过json.loadsast.literal(无效语法错误)。

我怎样才能加载这个?

edd*_*edd 3

如果数据的生产者是一致的,您可以从以下内容开始,旨在弥合 JSON 差距。

import re
import json


source = {
  "Records": "{Output=[{_fields=[{Entity=ABC  , No=12345, LineNo=       1, EffDate=20200630}, {Entity=ABC  , No=567, LineNo=       1, EffDate=20200630}]}"
}

s = source["Records"]

# We'll start by removing any extraneous white spaces
s2 = re.sub('\s', '', s)

# Surrounding any word with "
s3 = re.sub('(\w+)', '"\g<1>"', s2)

# Replacing = with :
s4 = re.sub('=', ':', s3)

# Lastly, fixing missing closing ], }
## Note that }} is an escaped } for f-string.
s5 = f"{s4}]}}"

>>> json.loads(s5)
{'Output': [{'_fields': [{'Entity': 'ABC', 'No': '12345', 'LineNo': '1', 'EffDate': '20200630'}, {'Entity': 'ABC', 'No': '567', 'LineNo': '1', 'EffDate': '20200630'}]}]}
Run Code Online (Sandbox Code Playgroud)

进行一些稳健的测试,并使用您最喜欢的工具进行完善的 ETL。