序列化與反序列化二json

2022-09-08 19:03:09 字數 2616 閱讀 4062

json格式的資料,所有的程式語言都能識別,本身是字串

型別有要求: int float bool str list tuple dict none

json與pickle的應用場景分別是什麼?

json 主要應用於傳輸資料 , 序列化成字串

pickle 主要應用於儲存資料 , 序列化成二進位制位元組流

#

json 基本用法

#json => dumps 和 loads

"""ensure_ascii=false 顯示中文 sort_keys=true 按鍵排序

"""dic =

res = json.dumps(dic,ensure_ascii=false,sort_keys=true)

print

(res , type(res))

dic =json.loads(res)

print

(dic , type(dic))

#json => dump 和 load

with open("

lianxi3.json

",mode="

w",encoding="

utf-8

") as fp:

json.dump(dic,fp,ensure_ascii=false)

with open(

"lianxi3.json

",mode="

r",encoding="

utf-8

") as fp:

dic =json.load(fp)

print

(dic , type(dic))

#### json 和 pickle 之間的區別

#1.json

#json 連續dump資料 , 但是不能連續load資料 , 是一次性獲取所有內容進行反序列化.

dic1 =

dic2 =

with open(

"lianxi4.json

",mode="

w",encoding="

utf-8

") as fp:

json.dump(dic1,fp)

fp.write("\n

")json.dump(dic2,fp)

fp.write("\n

")#不能連續load,是一次性獲取所有資料 , error

"""with open("lianxi4.json",mode="r",encoding="utf-8") as fp:

dic = json.load(fp)

"""#

解決辦法 loads(分開讀取)

with open("

lianxi4.json

",mode="

r",encoding="

utf-8

") as fp:

for line in

fp: dic =json.loads(line)

print

(dic,type(dic))

#2.pickle

import

pickle

#pickle => dump 和 load

#pickle 連續dump資料,也可以連續load資料

with open("

lianxi5.pkl

",mode="wb"

) as fp:

pickle.dump(dic1,fp)

pickle.dump(dic2,fp)

pickle.dump(dic1,fp)

pickle.dump(dic2,fp)

#方法一

"""with open("lianxi5.pkl",mode="rb") as fp:

dic1 = pickle.load(fp)

dic2 = pickle.load(fp)

print(dic1)

print(dic2)

"""#

方法二 (擴充套件)

"""try .. except .. 把又可能報錯的**放到try**塊中,如果出現異常執行except分支,來抑制報錯

"""#

一次性拿出所有load出來的檔案資料

try:

with open(

"lianxi5.pkl

",mode="rb"

) as fp:

while

true:

dic =pickle.load(fp)

print

(dic)

except

:

pass

json 和 pickle 兩個模組的區別?

(1)json序列化之後的資料型別是str,所有程式語言都識別,

但是僅限於(int float bool)(str list tuple dict none)

json不能連續load,只能一次性拿出所有資料

(2)pickle序列化之後的資料型別是bytes,用於資料儲存

所有資料型別都可轉化,但僅限於python之間的儲存傳輸.

pickle可以連續load,多套資料放到同乙個檔案中

json序列化與反序列化

1.什麼是序列化與反序列化?序列化就是將記憶體中的資料結構轉換成一種中間格式儲存到硬碟或者基於到網路傳輸。反序列化就是將硬碟中或者網路中傳來的一種資料格式轉換成記憶體中資料格式。2.為什麼要有序列化和反序列化?1.可以儲存程式的執行狀態。比如遊戲中使用者在某個狀態下線,使用者遊戲的資料需要儲存,這時...

json序列化 反序列化

json序列化 json的dumps方法可以將json格式資料序列為python的相關資料型別,比如str,常用於列印,另外,在序列化時,中文漢字被轉換為unicode編碼,在dumps函式中新增引數ensure ascii false可解決 dumps的indent參考可以調整顯示格式,即縮排,一...

JSON序列化與反序列化列舉

一 json序列化與反序列化列舉 1.這個示例使用了乙個jsonconverter定製如何序列化json與反序列化列舉 using system using system.collections.generic using system.linq using system.text using go...