Python 如何将字符串转为字典

Python 如何将字符串转为字典

在工作中遇到一个小问题,需要将一个 python 的字符串转为字典,比如字符串:

user_info = '{"name" : "json" , "gender": "male", "age": 28}'

我们想把它转为下面的字典:

user_info = {"name" : "json" , "gender": "male", "age": 28}

有以下几种方法:

  1. 通过 json 来转换
>>> import json
>>> user_info = '{"name" : "json" , "gender": "male", "age": 28}'
>>> user_dict = json.loads(user_info)
>>> user_dict
{'name': 'json', 'gender': 'male', 'age': 28}

但是使用 json 进行转换存在一个潜在的问题。

由于 json 语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号 (官网上有一段描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” ),因此下面的转换是错误的:

>>> user_info = "{'name' : 'json' , 'gender': 'male', 'age': 28}"
>>> user_dict = json.loads(user_info)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/miniconda3/envs/tf1.14/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/home/miniconda3/envs/tf1.14/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/home/miniconda3/envs/tf1.14/lib/python3.7/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
  1. 通过 literal_eval
>>> import ast
>>> user_info = '{"name" : "json" , "gender": "male", "age": 28}'
>>> user_dict = ast.literal_eval(user_info)
>>> user_dict
{'name': 'json', 'gender': 'male', 'age': 28}
>>> user_info = "{'name' : 'json' , 'gender': 'male', 'age': 28}"
>>> user_dict = ast.literal_eval(user_info)
>>> user_dict
{'name': 'json', 'gender': 'male', 'age': 28}

使用 ast.literal_eval 进行转换既不存在使用 json 进行转换的问题,也不存在使用 eval 进行转换的 安全性问题,因此推荐使用 ast.literal_eval。

posted @   michaelchengjl  阅读(587)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Blazor Hybrid适配到HarmonyOS系统
· 万字调研——AI生成内容检测
· 解决跨域问题的这6种方案,真香!
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
点击右上角即可分享
微信分享提示