1. 程式人生 > 實用技巧 >python json

python json

json 模組

Javascript Object Notation(標記)

java指令碼物件標記語言,將所有東西都變成字串形式

python中的set 集合無法用json表示出來

線性資料:

流式資料 "磁碟上的檔案" 一大堆0101010排列起來的

資料之間沒有引用關係

結構化資料:

記憶體中:

'abc'.upper() 字串

先把資料拆分出門 再把零件組裝

serialization deserialization

序列化: 將記憶體中的資料轉換成位元組串,用以儲存在檔案或通過網路傳輸,稱為序列化過程

反序列化 將檔案中或者網路中獲取的資料轉換成記憶體中原來的資料型別稱為反序列化的過程

從記憶體中 到記憶體中叫dumps 從記憶體中到檔案中叫dump

這裡有個生動形象的例子:

with open("a.txt", mode="wt", encoding="utf-8") as f:
    f.write(10)
wt: write text
wb: write binary   # t和b 表示資料的單位
a: append 
w: write 覆蓋寫模式  # w和r 表示資料的方向 是讀取還是寫入
r: read
+: 加個
預設是 rt格式

如果這麼寫程式碼,會報錯,顯示wirte必須為str資料型別

也就意味著 如果我們沒有字串型別的資料,json也就用不了,沒有意義.序列化的根本是位元組,json是一種不徹底的序列化方式

Serialization_demo.py

s = json.dumps([1, 2, 3]) 把指定的物件轉換為json格式的字串
print(type(s))
print(s)  #  '[1, 2, 3]'
print(s.split(','))

(venv) C:\work\day16>python Serialization_demo.py
<class 'str'>
[1, 2, 3]
['[1', ' 2', ' 3]']

看上去好像沒什麼區別,但實際上是字串
也就是 '[1, 2, 3]'

在強調一遍,並不是所有的資料型別都能轉化為json的字串

2. 元組

s = json.dumps((1, 2, 3))
print(s)

(venv) C:\work\day16>python Serialization_demo.py
[1, 2, 3]

json也能識別元組資料型別,將元組序列化後變成列表型別的字串

將列表轉換為元組

a = [1, 2, 3]
b = tuple(a)
print(type(a))

(venv) C:\work\day16>python Serialization_demo.py
<class 'list'>

3. 字典

s = json.dumps({'name': 'Andy', 'age': 10})
print(s)
print(type(s))

(venv) C:\work\day16>python Serialization_demo.py
{"name": "Andy", "age": 10}
<class 'str'>

4. 集合

s = json.dumps(set('abc'))

TypeError: Object of type set is not JSON serializable

(venv) C:\work\day16>
集合不可JSON序列化的型別

5.寫入到檔案dump

# 將json結果寫到檔案中
with open('a.txt', mode='at', encoding="utf-8") as f:
    json.dump([1, 2, 3], f)
    
    

發現當前目錄下自動寫入了一個txt檔案

2. 反序列化

2.1 List

# 反序列化
res = json.dumps([1, 2, 3])  # List序列化反序列化都是List
lst = json.loads(res)
print(type(lst))
print(lst)


a = '[1, 2, 3]'
b = str(a[1:])
c = str(b[:-1])
d = c.strip()
e = d.split(',')
print(e)

(venv) C:\work\day16>python Serialization_demo.py
<class 'list'>
[1, 2, 3]

2.2 元組

# 反序列化
res = json.dumps((1, 2, 3))
lst = json.loads(res)
print(type(lst))
print(lst)

(venv) C:\work\day16>python Serialization_demo.py
<class 'list'>
[1, 2, 3]

元組序列化後變成List樣的字串,反序列化後又變成List.無法回到元組型別

2.3 從檔案中反序列化

從記憶體中到記憶體中 loads

從檔案到記憶體 load


總結

# json
# json.dumps(obj)  # 記憶體到記憶體中
# json.dump(obj, f)  # 記憶體到檔案中
# json.loads()  # 記憶體中有一個數據轉為記憶體中
# json.load(f)  # 將f檔案中的格式回覆到原本的格式


# 把需要序列化的物件, 通過多次序列化的方式,用檔案的write方法把多次序列化後的字串寫到檔案中
with open('json.txt', mode='at', encoding='utf-8') as f:
    f.write(json.dumps([1, 2, 3]) + '\n')
    f.write(json.dumps([4, 5, 6]) + '\n')
    
# 為什麼要加 '\n'
如果不加的話將來讀取不回來了, 因為兩個中括號在一起了

# 把分次序列化的json字串, 反序列化回來
with open('json.txt', mode='rt', encoding='utf-8') as f:
    res = json.loads(f.readline().strip())
    res2 = json.loads(f.readline().strip())
    print(type(res))
    print(res)
    print(type(res2))
    print(res2)
    
做法二:
with open('json.txt', mode='rt', encoding='utf-8') as f:
    for x in f:
        print(json.loads(x.strip()))

反序列化過程