[python] How to convert a string into a dictionary

background:

When learning Django, according to the input json data, the backend stores the data, and found that the json data read by the backend is of string type, even if I use the json.loads() method to convert it, it is not converted into a dictionary type

That's when I realized I had to summarize and record.

Use json.loads() to convert

data='{"name":"fancy","age":18,"home":"china"}'

json_data=json.loads(data)
print("json转化成字典",json_data)
print("json转化成字典的类型",type(json_data))

 result:

json is converted into a dictionary {'name': 'fancy', 'age': 18, 'home': 'china'}
json is converted into a dictionary type <class 'dict'>

Use eval() to convert

data='{"name":"fancy","age":18,"home":"china"}'
dic_data=eval(data)
print("使用eval转化成字典",dic_data)
print("使用eval转化成字典的类型",type(dic_data))

 result:

Use eval to convert to dictionary {'name': 'fancy', 'age': 18, 'home': 'china'}
Use eval to convert to dictionary type <class 'dict'>

 However, although eval() is convenient, there may be security issues , because no matter what you enter, it will be converted into a type that python can recognize

For example this code:

input_info=input("os.path.realpath(__file__)")
dic_data=eval(input_info)

The output is: Use eval to convert into a dictionary /Users/xmly/Desktop/tools/05_jiami/basic knowledge.py

It is conceivable that if the input is a code command to obtain data or a command to delete data, then there will be a serious security risk

Later we can use the ast.literal_eval() method

Convert using ast.literal_eval()

If you use ast.literal_eval() and then do the above:

input_info=input("os.path.realpath(__file__)")
dic_data=ast.literal_eval(input_info)

The program will report an error, which prevents unsafe command input:

 Convert string normally:

data='{"name":"fancy","age":18,"home":"china"}'
dic_data=ast.literal_eval(data)
print("使用literal_eval转化成字典",dic_data)
print("使用literal_eval转化成字典的类型",type(dic_data))

result:

Use literal_eval to convert to dictionary {'name': 'fancy', 'age': 18, 'home': 'china'}
Use literal_eval to convert to dictionary type <class 'dict'>

Guess you like

Origin blog.csdn.net/weixin_43569834/article/details/131132126