首页 > 代码库 > json,pickle

json,pickle

json

 将python基本数据类型转换成字符串形式

import json

dict = {‘k1‘:‘v1‘}
result = json.dumps(dict)
print(result,type(result))

 

将python字符串转换成基本数据类型

s1 = ‘{"k1":123}‘
dic = json.loads(s1)
print(dic,type(dic))


 dump先写入文件在转换 import json


li = [11,22,33]
json.dump(li,open(‘b.txt‘,‘w‘))

 

load先读取在转换

li = json.load(open(‘b.txt‘,‘r‘))
print(type(li),li)

 

用途

import requests
import json

response = requests.get(‘http://wthrcdn.etouch.cn/weather_mini?city=上海‘)
response.enconding = ‘utf-8‘

dic = json.loads(response.text)
print(dic,type(dic))

 

pickle 只支持python json可以跨语言 

pickle使用python所有类型的序列化

pickle

import pickle

li = [11,22,33]
r = pickle.dumps(li)
print(r)

result = pickle.loads(r)
print(result)

li = [11,22,33]
pickle.dump(li,open(‘b.txt‘,‘wb‘))

 

json,pickle