我在下面有一个没有引号的嵌套字符串字典,我想把它转换成python字典。
{ id: 0,
label: 'Data0',
axis: "left",
color: "#0000ff",
avg: "383.04347826086956",
last: "378.0",
min: "282.0",
max: "439.0" }
,
{ id: 1,
label: 'Data1',
axis: "left",
color: "#00ff00",
avg: "",
last: "",
min: "",
max: "" }
预期输出:
{ "id": 0,
"label": "Data0",
"axis": "left",
"color": "#0000ff",
"avg": 383.04347826086956,
"last": 378.0,
"min": 282.0,
"max": 439.0 }
,
{ "id: 1,
"label": "Data1",
"axis": "left",
"color": "#00ff00",
"avg": "",
"last": "",
"min": "",
"max": "" }
这样做的主要原因是从API响应中获得字符串形式的输出,其中包含我使用split()方法删除的许多其他内容。
尝试:
js_data = """
/*
* Pure Javascript, which calls the specified callback function, specified using the Jsonp parameter
*
* Callback function is passed all parameters necessary to render chart
*/
MP.ChartController.loaded('chartdiv',
{
error: '',
width: 1480,
height: 308,
summaryData: [
{
id: 0,
label: 'Data0',
axis: "left",
color: "#0000ff",
avg: "383.04347826086956",
last: "378.0",
min: "282.0",
max: "439.0"
},
{
id: 1,
label: 'PQ Initiated',
axis: "left",
color: "#00ff00",
avg: "",
last: "",
min: "",
max: ""
}
],
graphType: 'chart',
warnings: []
});
"""
import re
import json
# find `summaryData`
summary_data = re.search(r"summaryData: ([.*?]),", js_data, flags=re.S)
# add quotes("") around keys
summary_data = re.sub(r"(S+):", r'"1":', summary_data.group(1))
# replace ' to "
summary_data = summary_data.replace("'", '"')
# decode the string:
summary_data = json.loads(summary_data)
print(summary_data)
打印:
[
{
"id": 0,
"label": "Data0",
"axis": "left",
"color": "#0000ff",
"avg": "383.04347826086956",
"last": "378.0",
"min": "282.0",
"max": "439.0",
},
{
"id": 1,
"label": "PQ Initiated",
"axis": "left",
"color": "#00ff00",
"avg": "",
"last": "",
"min": "",
"max": "",
},
]