1. 程式人生 > >模塊講解----json模塊(跨平臺的序列化與反序列化)

模塊講解----json模塊(跨平臺的序列化與反序列化)

/usr 列表 strong 序列化 類型轉換 min 字符 虛擬 json

一、json的特點

1、只能處理簡單的可序列化的對象;(字典,列表,元祖) 2、json支持不同語言之間的數據交互;(python - go,python - java) 二、使用場景 1、玩遊戲的時候存檔和讀取記錄。 2、虛擬機掛起、保存或者恢復、讀檔的時候。 三、語法: 1、簡單的數據類型:
 1 1、在內存中進行轉換:
 2 import json
 3 #py基本數據類型轉換字符串:
 4 r = json.dumps([11,22,33])
 5 #li = ‘["alex","eric"]‘
 6 li = "[‘alex‘,‘eric‘]"
 7 re = json.loads(li)   #
反序列化的時候,一定要使用雙引號""。 8 print(re,type(re)) 9 10 11 2、在文件中轉換:(在dumps和loads基礎上增加了個寫讀文件) 12 import json 13 14 文件格式的序列化: 15 li = [11,22,33] 16 json.dump(li,open(db,w)) 17 18 19 文件格式的反序列化: 20 li = json.load(open(db,r)) 21 print(li,type(li))

2、復雜的數據類型:

序列化:

 1 #!/usr/bin/env python
 2 # -*- coding:utf8 -*-
3 # Author:Dong Ye 4 5 import json 6 7 8 test = rtest.txt 9 10 info = { 11 name : alex, 12 age : 32 13 14 } 15 16 with open(test,w,encoding=utf-8) as f: 17 f.write( json.dumps(info) )

反序列化:

 1 #!/usr/bin/env python
 2 # -*- coding:utf8 -*-
 3 # Author:Dong Ye
 4
5 import json 6 7 test = rtest.txt 8 9 with open(test,r,encoding=utf-8) as f: 10 data = json.loads( f.read() ) 11 print(data) 12 print(data[name]) 13 print(data[age])

使用場景

調用其他平臺的接口時,一般都會返回一個字符串,eg:“字典,列表,url路徑等”。
1 import requests
2 import json
3 
4 response = requests.get("http://http://wthrcdn.etouch.cn/weather_mini?ciyp=北京")
5 response.encoding = utf-8
6 
7 dic = json.loads(requests.text)
8 print(response,type(response))

模塊講解----json模塊(跨平臺的序列化與反序列化)