python字符串(js变量类型)到字典
如何将此字符串转换为字典
我正在尝试正则表达式 r"},\s\]"
,但没有得到所需的结果。
HTTP 请求正文
内容类型:text/html
var sample = {
"date": "2022. 03. 23. 16:18",
"list":
[
{
"name": "USD",
"var1":"1236.26",
"var2":"1193.74",
"var3":"1226.90",
"var4":"1203.10",
"var5":"1215.00"
},
{
"name": "JPY",
"var1":"1020.81",
"var2":"985.71",
"var3":"1013.09",
"var4":"993.43",
"var5":"1003.26"
},
]
}
How do I convert this string to a dictionary
I'm trying regex r"},\s\]"
, but didn't get the desired result.
HTTP request body
Content-Type: text/html
var sample = {
"date": "2022. 03. 23. 16:18",
"list":
[
{
"name": "USD",
"var1":"1236.26",
"var2":"1193.74",
"var3":"1226.90",
"var4":"1203.10",
"var5":"1215.00"
},
{
"name": "JPY",
"var1":"1020.81",
"var2":"985.71",
"var3":"1013.09",
"var4":"993.43",
"var5":"1003.26"
},
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,我们需要去掉所有尾随逗号:
您也可以使用正则表达式:
然后使用 json.loads() 将其解析为字典。
超越 OQ
如果我们也可能在字典的最后一个键值后面有尾随逗号:例如
{"var5": "1215.00",}
您可以将上面的代码更新为:或者使用正则表达式:
First we need to get rid of any trailing commas:
You can also use regex for this:
Then use
json.loads()
to parse it into a dict.Beyond the OQ
If it is also possible that we'd have trailing commas after the last key-value of a dictionary: e.g.
{"var5": "1215.00",}
you can update the above code to:Or with regex: