博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python将字符串转为字典最佳实践
阅读量:7071 次
发布时间:2019-06-28

本文共 2941 字,大约阅读时间需要 9 分钟。

在工作中我们经常会遇到数据类型之间的互转的问题,而通常我们请求一些API借口返回的结果就是字符串,但是格式是Json的,在Python中转为字典是最易处理的,所以这里记录一下在Python下把字符串转为字典的三种方法。

方法一: 通过内置函数eval

Source Code:

#!/usr/bin/env python3#Author: nock.chenstr_info = "{'name': 'nock', 'age': 14}"dict_info = eval(str_info)print("string info type is -->: %s" % (type(str_info)))print("dict info type is -->: %s" % (type(dict_info)))复制代码

Result:

string info type is -->: 
dict info type is -->:
复制代码

不过使用eval有一个安全性问题,示例如下:

Source Code:

#!/usr/bin/env python3#Author: nock.chenstr_info = input('input str info: ')dict_info = eval(str_info)print("dict_info is >%s< " % dict_info)复制代码

Result:

input str info: __import__('os').system('ls')collector_data.pytest.pyDownloaddict_info is >0< 复制代码

如上所示当我们输入__import__('os').system('ls')的时候会打印出脚本所存目录下的文件,如果传入一个rm -rf *之类的命令,那则会把所有改目录下的东西删除掉;当然我们这么去用的场景会非常好少,也不可能有人会这么传值,不过这里说明一下。

方法二: 通过json模块处理

Source Code:

#!/usr/bin/env python3#Author: nock.chenimport jsonstr_info = '{"name": "nock", "age": 18}'dict_info = json.loads(str_info)print("string info type is -->: %s" % (type(str_info)))print("dict info type is -->: %s" % (type(dict_info)))复制代码

Result:

string info type is -->: 
dict info type is -->:
复制代码

使用json模块进行转换也存在一个问题,由于json语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号, 上有一段描述是:

报错示例如下:

#!/usr/bin/env python3#Author: nock.chenimport jsonstr_info = "{'name': 'nock', 'age': 18}"dict_info = json.loads(str_info)复制代码

报错结果如下:

Traceback (most recent call last):  File "test.py", line 7, in 
dict_info = json.loads(str_info) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 319, in loads return _default_decoder.decode(s) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx)json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)复制代码

方法三: 通过ast模块处理

Source Code:

#!/usr/bin/env python3#Author: nock.chenimport aststr_info = '{"name": "nock", "age": 18}'dict_info = ast.literal_eval(str_info)print("string info type is -->: %s" % (type(str_info)))print("dict info type is -->: %s" % (type(dict_info)))s_info = "{'name': 'nock', 'age': 18}"d_info = ast.literal_eval(s_info)print("s info type is -->: %s" % (type(s_info)))print("d info type is -->: %s" % (type(d_info)))复制代码

Result:

string info type is -->: 
dict info type is -->:
s info type is -->:
d info type is -->:
复制代码

使用ast.literal_eval进行转换既不存在使用json 模块进行转换的问题,也不存在使用eval模块进行转换的安全性问题,因此推荐大家使用ast.literal_eval的方法。

转载于:https://juejin.im/post/5b34d3f86fb9a00e38584924

你可能感兴趣的文章
获取GridView控件总列数
查看>>
Vim 中使用cscope
查看>>
HR系统+人脸识别
查看>>
RabbitMQ与AMQP协议详解
查看>>
metronic后台模板学习 -- 所用外部插件列表
查看>>
微软原版SQLHelper类
查看>>
首页设计的可用性和PET
查看>>
mongodb的分布式集群(1、主从复制)
查看>>
http://www.cnblogs.com/yaozhenfa/archive/2015/06/14/4574898.html
查看>>
使用自定义tld标签简化jsp的繁琐操作
查看>>
Div Vertical Menu ver3
查看>>
动态为DropDownList添加Item
查看>>
spring NotWritablePropertyException异常
查看>>
TCP是如何保证可靠传输的
查看>>
【Python】爬取理想论坛单帖爬虫
查看>>
php实现 24点游戏算法
查看>>
学习ASP.NET Core Razor 编程系列十七——分组
查看>>
酷壳网陈皓:开发者实用学习资源汇总
查看>>
CAS Maven
查看>>
杭电1018 Big Number
查看>>