需求:把以下字符串轉換為字典
#字符串 testStr = '{ "pName": "Ceshi", "gender": 1, "country": 156, "countryType": 1, "nation": 1, "province": "北京市" }'
轉換為:testDic = { "pName": "Ceshi", "gender": 1, "country": 156, "countryType": 1, "nation": 1, "province": "北京市" }
方法1:通過 json 轉換
import json testDic = json.loads(testStr)
缺點:json 規定 由零個或多個Unicode字符組成的字符串,需要用雙引號括起來,使用反斜杠轉義。
如果字符串中用單引號會報錯:json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes。
方法2:通過eval轉換
testDic = eval(testStr)
缺點:存在安全問題,eval在轉換類型的同時可以執行字符串中帶有的執行語句,如下:
test = eval("print('傻')") print(test) '''
執行結果: 傻 None
'''
方法3:通過as.literal_eval()轉換(推薦)
import ast testDic = ast.literal_eval(testStr)