Python之json模块

一、序列化需求

假如有一个其它语言编写很大的字典,通过网络传输协作开发,使用前需要转换成字典。

dic = {'name': 'lin', 'age': 25, 'sex': ''}
ret = str(dic).encode('utf-8')                            # 传输过来之后是byte类型

ret1 = ret.decode('utf-8')
print(ret1, type(ret1))                                   # 通过此方法,只能取到字符串类型,可以使用eval()方法,但是不建议。

----------------------执行结果-------------------------
{'name': 'lin', 'age': 25, 'sex': ''} <class 'str'>
------------------------------------------------------

二、使用json模块,适用于所有语言

2.1  dumps和loads主要用于网络传输;将重要的数据变成可以传输的,并且得到后能够反解出来。

import json
dic = {'name': 'lin', 'age': 25, 'sex': ''}
ret = json.dumps(dic)
print(ret, type(ret))

----------------------执行结果-------------------------
{"name": "lin", "age": 25, "sex": "\u7537"} <class 'str'>   # 序列化就是变成一个特殊的字符串
------------------------------------------------------

ret = json.dumps(dic, ensure_ascii=False)                   # 设置ensure_ascii
print(ret, type(ret))
----------------------执行结果-------------------------
{"name": "lin", "age": 25, "sex": ""} <class 'str'>
------------------------------------------------------

respon = json.loads(ret)                                    # 使用loads进行反序列化,反解成原来的类型
print(respon, type(respon))
print(respon.get('name'))
----------------------执行结果-------------------------
{'name': 'lin', 'age': 25, 'sex': ''} <class 'dict'>
lin
------------------------------------------------------

2.2 dump和load用于写入文件操作

dic = {'Request_Server_Name': 'www.abc.com', 'Request_Server_Host': '1.1.1.1', 'Request_Server_Port': '443',
        'Forward_Real_WebServer': '10.10.10.1', 'Request_Real_Client': '2.2.2.2', 'Requests_number': 1,
        'Request_Size': 1024, 'Requst_Return_Status_Code': 200, 'Request_Mothod': 'GET /'
       }

with open('access.log', 'w') as f:
    json.dump(dic, f)                                        # dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件

------------------------------------------------------
with open('access.log', mode='r') as f:
    dic2 = json.load(f)                                      # load方法读取文件句柄,直接将文件中的json字符串转换成数据结构返回
    print(type(dic2))
    print(dic2.get('Request_Size'))
----------------------执行结果-------------------------
<class 'dict'> 1024
------------------------------------------------------

 

posted @ 2019-03-07 21:17  林中龙虾  阅读(258)  评论(0编辑  收藏  举报