在日常使用Python的过程中,有时会遇到这种需求。将一个字符串转换为字典格式。
举例
- str = "{'id': 123, 'name': 'Tom', 'age': 12}"
- print(type(str))
-
- # 运行结果
-
- <class 'str'>
下面介绍几种将字符串转为字典的方法并介绍相关注意事项。
目录
1.使用json
2.使用eval
3.使用literal_eval
1.使用json
第一种情况
- import json
-
- str = '{"id": 123, "name": "Tom", "age": 12}'
- print(type(str))
- str_c = json.loads(str)
- print(type(str_c))
-
- # 运行结果
-
- <class 'str'>
- <class 'dict'>
第二种情况
- import json
-
- str = "{'id': 123, 'name': 'Tom', 'age': 12}"
- print(type(str))
- str_c = json.loads(str)
- print(type(str_c))
-
- # 运行结果
-
- json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
可以看出第一种情况运行正常,格式转换成功,而第二种却报错。
解释:其官网上有一段描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” ,因此 json 语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号。
2.使用eval
- str = "{'id': 123, 'name': 'Tom', 'age': 12}"
- print(type(str))
- str_c = eval(str)
- print(type(str_c))
-
- # 运行结果
-
- <class 'str'>
- <class 'dict'>
注意:使用eval存在安全隐患。
3.使用literal_eval
- import ast
-
- str = "{'id': 123, 'name': 'Tom', 'age': 12}"
- print(type(str))
- str_c = ast.literal_eval(str)
- print(type(str_c))
-
- # 运行结果
-
- <class 'str'>
- <class 'dict'>
注意:当键值有空值时不能使用literal_eval。