python - 带单引号且不带转义字符的 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
有多个单引号。
我想的一种方法是使用正则表达式和反向传播。有没有其他方法可以将这种类型的字符串转换为子对象。
解决方案
这种使用 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))
推荐阅读
- arrays - 在解决 c 中查找和计算重复项时面临运行时错误
- racket - Typed Racket 中的“n”是什么意思?
- android - Android 客户端无法使用套接字连接到服务器
- machine-learning - Weka 3.8 - 决策树 J48 似乎有正确的树来预测数据但在测试中失败
- json - VS Code 扩展中自动换行的自定义原因,以便在 Json 中使用多行值
- elasticsearch - 如何在弹性搜索文本搜索中匹配部分单词
- angular - 如何在 Angular Typescript 中传递模型名称
- excel - 检查表 1 中的日期是否在一个月内,表 2 中的日期旁边的返回值
- docker - .NET Core API docker 无法访问
- macos - 如何在 MacOS BigSur 的聚光灯下禁用网络搜索