需求:把以下字符串转换为字典
#字符串 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)