一、字符串str转为字典dict
1、使用json进行转换
import json
a = '{"a":"1", "b":"1"}'
c=json.loads(a)
print(c, type(c))
输出:
{‘a’: ‘1’, 'c: ‘1’} <class ‘dict’>
user_info = "{'name' : 'john', 'gender' : 'male', 'age': 28}"
user_dict =json.loads(user_info )
print(user_dict , type(user_dict ))
报错:Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
使用json转字典是报错,因为里面不是双引号,此时使用eval则不会报错
2、使用eval进行转换
(1)操作步骤
a = '{"a":"1", "b":"1"}'
b = eval(a)
print(b, type(b))
输出:
{‘a’: ‘1’, ‘b’: ‘1’} <class ‘dict’>
user_info = "{'name' : 'john', 'gender' : 'male', 'age': 28}"
user_dict = eval(user_info)
print(user_dict , type(user_dict ))
(2)安全隐患
- 运行程序,如果用户恶意输入:
please input:__import__('os').system('dir')
则eval()之后,当前目录文件都会展现在用户前面。
演示结果:
- 运行程序,如果用户恶意输入:
please input:open('data.py').read()
如果,当前目录中恰好有一个文件,名为data.py,则恶意用户变读取到了文件中的内容。
演示结果:
3、使用 literal_eval进行转换
import ast
user = '{"name" : "john", "gender" : "male", "age": 28}'
user_dict = ast.literal_eval(user)
print(user_dict,type(user_dict))
输出:{‘name’: ‘john’, ‘gender’: ‘male’, ‘age’: 28} <class ‘dict’>
使用 ast.literal_eval 进行转换既不存在使用 json 进行转换的问题,也不存在使用 eval 进行转换的 安全性问题
二、字典转化为字符串
c = {'a': '1', 'b': '1'}
b=str(c)
print(b,type(b))
输出:{‘a’: ‘1’, ‘b’: ‘1’} <class ‘str’>
c = {'a': '1', 'b': '1'}
b = json.dumps(c)
print(b,type(b))
输出:{“a”: “1”, “b”: “1”} <class ‘str’>
三、字符串双引号替换单引号
user = '{"name" : "john", "gender" : "male", "age": 28}'
print(user,type(user))
user = user.replace('"',"'")
print(user,type(user))
user = user.replace("'",'"')
print(user,type(user))
输出:
{“name” : “john”, “gender” : “male”, “age”: 28} <class ‘str’>
{‘name’ : ‘john’, ‘gender’ : ‘male’, ‘age’: 28} <class ‘str’>
{“name” : “john”, “gender” : “male”, “age”: 28} <class ‘str’>
参考文献:
https://blog.csdn.net/zoulonglong/article/details/80446373