[英]JSON object with single quotes without escape characters
我正在尝试从实时流中接收到的原始字符串中创建子对象进行处理。 我正在处理的字符串是:
{‘check_1’:{‘key_1’:15017.118,‘key_2’:’HTTPConnectionPool(host=‘host_1’, port=80): Read timed out. (read timeout=15)’,’key_3’:’Some reason here’}}
我试图用类似的东西用双引号替换单引号
str = str.replace(",'", ',"').replace("',", '",')
str = str.replace(":'", ':"').replace("':", '":')
str = str.replace("{'", '{"').replace("'}", '"}')
但是当我执行json.loads(str)
时, key_2
值会导致问题,因为key_2
值有多个单引号。
我想的一种方法是使用正则表达式和反向传播。 有没有其他方法可以将这种类型的字符串转换为子对象。
这个带有 re 库的快速 hack 似乎有效
import re
thestring = re.sub(r'[‘’]', '"', thestring) # don't call your variable str
thestring = re.sub(r'="(\S+)"', r"='\1'", thestring)
print( json.loads(thestring))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.