Python中用于序列化的两个模块
- json 用于【字符串】和 【python基本数据类型】 间进行转换
- pickle 用于【python特有的类型】 和 【python基本数据类型】间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
json.dudmp ("[11,22]",open('db.txt','w')) #转换成字符串再保存到该文件。
json.load(open('db.txt','r')) #打开该文件装成字符串。
import json
s="{"k1":"123"}" #注,字典里面的字符必须用双引号引起来才可以转换成json.
l="[11,22,33,44]" result = json.loads(1)#用于将字典,列表,元组形式的字符串转化成字典,列表,元组。
st = json.dumps(l) # 把列表转化成json格式的字符串。
print (result,type(result))
从接口接收值.py
import urllib.request import json req = urllib.request.Request('http://www.baidu.com/api") r = urlib.request.urlopen(req) result = str(r.read(),encoding="utf-8" dic = json.load(reesult) print (dic)
import pickle data={'k1':123} with open('xx.pk','wb') as w: pickle.dump(data,w)
requests 模块:
requests.get("http://www.baidu.com")
requests.encoding='utf-8'
print (requests.text)
XML模块:
from xml.etree import ElementTree as ET r = requests.get('http://www.webxml.com') result = r.text #返回个XML的对象 node = ET.XML(result) if node.text == "Y" print ('在线') else: print ('离线')