python--字符串转换为字典

 1 # 将一个python的字符串转为字典,
 2 # 比如字符串:
 3 user_info = '{"name" : "john", "gender" : "male", "age": 28}'
 4 # 我们想把它转为下面的字典:
 5 
 6 user_dict = {"name" : "john", "gender" : "male", "age": 28}
 7 
 8 # 1. 通过 json 来转换
 9 # 但是使用 json 进行转换存在一个潜在的问题。
10 # 由于 json 语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号
11 # (官网上有一段描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” )
12 
13 
14 # 2、通过 eval
15 # 通过 eval 进行转换就不存在上面使用 json 进行转换的问题。但是,使用 eval 却存在安全性的问题
16 
17 
18 # 3. literal_eval
19 import ast
20 user = '{"name" : "john", "gender" : "male", "age": 28}'
21 user_dict = ast.literal_eval(user)
22 print(type(user_dict))
23 print(user_dict['name'])

https://wenku.baidu.com/view/58d53b5b24284b73f242336c1eb91a37f0113273.html

posted @ 2022-04-19 19:09  WJ-HAHA  阅读(4084)  评论(0编辑  收藏  举报