首页 > 解决方案 > 带单引号且不带转义字符的 JSON 对象

问题描述

我正在尝试从我在实时流中接收到的原始字符串中创建子对象以进行处理。我正在处理的字符串是:

{‘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("'}", '"}')

key_2但是当我这样做时value for会导致问题,json.loads(str)因为 value ofkey_2有多个单引号。

我想的一种方法是使用正则表达式和反向传播。有没有其他方法可以将这种类型的字符串转换为子对象。

标签: pythonjsonstring

解决方案


这种使用 re 库的快速破解似乎有效

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))

推荐阅读