python - 将字符串转换为 Python 字典
问题描述
此代码返回一个 str 作为类型。给定任务的格式,如何将其转换为 python 字典?
import json
tasks = '''{'key1': 'val1', 'key2': None}'''
new_tasks = tasks.replace("'", "\"")
new_tasks = new_tasks.replace('None', 'null')
new_tasks = json.dumps(new_tasks)
new_tasks = json.loads(new_tasks)
print(type(new_tasks))
注意:我宁愿不使用 ast.literal_eval 或 ast.eval。
解决方案
import json
tasks = '''{'key1': 'val1', 'key2': None}'''
new_tasks = tasks.replace("'", "\"")
new_tasks = new_tasks.replace('None', 'null')
# new_tasks = json.dumps(new_tasks)
new_tasks = json.loads(new_tasks)
print(type(new_tasks))
正如Barmar所说,转储将其双引号括起来
输出:
<class 'dict'>
推荐阅读
- javascript - 这个 for in Loop 如何使用 JavaScript 中的快速排序对数字进行排序
- laravel - 我如何避免此错误尝试获取非对象的属性“id”?
- python - Pygame在执行程序后运行缓慢
- python - 如果硒无法找到元素,我如何避免关闭硒
- javascript - 渲染 svgs 并在 React 组件中设置内部 css .this
- c++ - 为什么 pop_back() 在此代码中不起作用?
- linux - iostats 显示逻辑卷的写入次数多于其下的物理卷
- qt - QTCPSocket - 当主机连接到单独的网络时如何强制连接到特定的网络
- java - 这只是一个错字吗?
- javascript - 根据另一个元素的焦点/活动状态更改一个元素的 CSS