简体   繁体   English

将格式错误的字符串解析为 python 中的 dict

[英]parsing malformed string to dict in python

I'm parsing some logs and one of them returns a badly formatted dict as a string:我正在解析一些日志,其中一个将格式错误的 dict 作为字符串返回:

to_parse = '{ name: \"test1\", description_code: \"\", id_code: 1v3fELLZxyY }'

what's the best way to convert this string to a proper dict() ?将此字符串转换为正确的dict()的最佳方法是什么?

parsed = { 'name' : 'test1', 'description_code' : '', 'id_code' : '1v3fELLZxyY'}

Assuming that to_parse would always be just top level JSON, you may use a regex replacement here:假设to_parse总是只是顶级 JSON,您可以在这里使用正则表达式替换:

import re

to_parse = '{ name: \"test1\", description_code: \"\", id_code: 1v3fELLZxyY }'
output = re.sub(r'(?<!\S)(\w+)(?=:|\s|$)', r'"\1"', to_parse)
print(output)
# { "name": "test1", "description_code": "", "id_code": "1v3fELLZxyY" }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM