2022年 11月 5日

Python几种常见的字符串转换字典方法

在日常使用Python的过程中,有时会遇到这种需求。将一个字符串转换为字典格式。

举例

  1. str = "{'id': 123, 'name': 'Tom', 'age': 12}"
  2. print(type(str))
  3. # 运行结果
  4. <class 'str'>

下面介绍几种将字符串转为字典的方法并介绍相关注意事项

目录

1.使用json

2.使用eval

3.使用literal_eval


1.使用json

第一种情况

  1. import json
  2. str = '{"id": 123, "name": "Tom", "age": 12}'
  3. print(type(str))
  4. str_c = json.loads(str)
  5. print(type(str_c))
  6. # 运行结果
  7. <class 'str'>
  8. <class 'dict'>

第二种情况

  1. import json
  2. str = "{'id': 123, 'name': 'Tom', 'age': 12}"
  3. print(type(str))
  4. str_c = json.loads(str)
  5. print(type(str_c))
  6. # 运行结果
  7. 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

  1. str = "{'id': 123, 'name': 'Tom', 'age': 12}"
  2. print(type(str))
  3. str_c = eval(str)
  4. print(type(str_c))
  5. # 运行结果
  6. <class 'str'>
  7. <class 'dict'>

注意:使用eval存在安全隐患。

3.使用literal_eval

  1. import ast
  2. str = "{'id': 123, 'name': 'Tom', 'age': 12}"
  3. print(type(str))
  4. str_c = ast.literal_eval(str)
  5. print(type(str_c))
  6. # 运行结果
  7. <class 'str'>
  8. <class 'dict'>

注意:当键值有空值时不能使用literal_eval。