python3之json模組使用

來源:互聯網
上載者:User

標籤:分隔字元   c11   ocs   false   name   size   too   關係   string   

 

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/pythonimport jsonif __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/pythonimport jsonif __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/pythonimport jsonif __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

對於自訂類型的序列化,一般都是使用第三方庫,當然這個是另外的內容了。

 

 

參考資料:

1. https://docs.python.org/2/library/json.html

python3之json模組使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.