使用 json 模块
字符串转字典
import jsons = '{"name": "Johel Liang", "Sex": "Man"}'d = json.loads(s)print(d, ',', d['name'])# {'name': 'Johel Liang', 'Sex': 'Man'} , Johel Liang
字典转字符串
import jsond = {'name': 'Johel Liang', 'Sex': 'Man'}s = json.dumps(d)print(s)# {"name": "Johel Liang", "Sex": "Man"}# 也可以用 str(d) 强转换
使用 eval 方法
使用 json 对字符串进行转换,如果字典格式不严格(如字典使用单引号),就可能会出现如下报错:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
所以,有时我们会使用eval方法对字符串进行转换,示例如下:
s = '{"name": "Johel Liang", "Sex": "Man"}'d = eval(s)print(d, d['name'])# {'name': 'Johel Liang', 'Sex': 'Man'} , Johel Liang
注:使用 eval 方法存在一定的安全隐患,能使用 json 便尽量使用 json 模块
如果觉得《【script】python 使用json模块实现字符串与字典的相互转换》对你有帮助,请点赞、收藏,并留下你的观点哦!