Python如何將字符串(str/json)轉換字典(dict)

一、字符串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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章