1. json模塊介紹
json是python自帶的操作json的模塊。
python序列化為json時的數據類型轉換關系:
| python格式 | json格式 |
| dict(復合類型) | object |
| list, tuple(集合類型) | array |
| int, long, float(數值類型) | number |
| str, unicode | string |
| True | true |
| False | false |
| None | null |
json反序列化為python數據類型對照關系:
| json格式 | python格式 |
| object | dict |
| array | list |
| string | unicode |
| number(int) | int, long |
| numer(real) | float |
| true | True |
| false | False |
| null | None |
2. 如何使用
json庫提供了幾個API:
json.dumps(): 將字典序列化為json字符串
json.loads(): 將json字符串反序列化為字典
json.dump(): 將字典序列化到一個文件,是文本文件,就是相當於將序列化后的json字符串寫入到一個文件
json.load(): 從文件中反序列出字典
總結: 不帶s的是序列到文件或者從文件中反序列化,帶s的是都在內存中操作不涉及到持久化
一個簡單使用的例子如下:
#! /usr/bin/python
import json
if __name__ == '__main__':
cc = {
"name": "CC11001100",
"age": 22,
"money": 9.9,
"car": "Feng-Huang Bicycle",
"house": "祖宅",
"girl friend": None,
"hobby": "thinking..."
}
# 序列化為字符串
json_string = json.dumps(cc)
print(json_string)
# 從字符串中反序列化
json_dict = json.loads(json_string)
print(json_dict)
# 序列化到文件中
with open('D:/cc.json', 'w') as json_file:
json.dump(cc, json_file)
# 從文件中反序列化
with open('D:/cc.json', 'r') as json_file:
json_dict = json.load(json_file)
print(json_dict)
py對象序列化為json的時候會接受的幾個參數:
indent: 即縮進量是幾個空格,當需要格式化輸出的時候一般設為4個空格
一個指定indent的小例子:
#! /usr/bin/python
import json
if __name__ == '__main__':
cc = {
"name": "CC11001100",
"age": 22,
"money": 9.9,
"car": "Feng-Huang Bicycle",
"house": "祖宅",
"girl friend": None,
"hobby": "thinking..."
}
print(json.dumps(cc, indent=4))
輸出:
{
"name": "CC11001100",
"age": 22,
"money": 9.9,
"car": "Feng-Huang Bicycle",
"house": "\u7956\u5b85",
"girl friend": null,
"hobby": "thinking..."
}
separators: 生成的json子串所使用的分隔符,就是用來代替分隔多個k/v對的,和分隔k/v的:
一個指定了separators的小例子:
#! /usr/bin/python
import json
if __name__ == '__main__':
cc = {
"name": "CC11001100",
"age": 22,
"money": 9.9,
"car": "Feng-Huang Bicycle",
"house": "祖宅",
"girl friend": None,
"hobby": "thinking..."
}
print(json.dumps(cc, indent=4, separators=('↓', '→')))
輸出:
{
"name"→"CC11001100"↓
"age"→22↓
"money"→9.9↓
"car"→"Feng-Huang Bicycle"↓
"house"→"\u7956\u5b85"↓
"girl friend"→null↓
"hobby"→"thinking..."
}
sort_keys:是否對key進行排序,目前還沒感覺出有啥用
3. 自帶json模塊的局限性
使用自帶的json模塊雖然很方便,但是序列化自定義類型的時候就會拋出一個TypeError的異常:
TypeError: Object of type 'Person' is not JSON serializable
對於自定義類型的序列化,一般都是使用第三方庫,當然這個是另外的內容了。
參考資料:
