Python-json模組

來源:互聯網
上載者:User

標籤:小練習   load   load()   要求   ascii   雙引號   轉化   引入   file   

json串是任何語言都可以識別的,因此json模組是一個重要的模組。

json串實際上就是字串。

1、json格式

json格式如下,必須使用雙引號。

2、讀json檔案

讀取json檔案後,資料類型是字串類型。可以引入json模組,用json.loads或者json.load將其變為字典類型。

例:有一個檔案products.json。

(1)用json.loads()

用read將檔案讀出來,然後把讀出來的資料用json.loads()轉換為字典類型。

通過運行結果可以看出,讀出啦的res格式是字串,json.loads()將其轉化為字典格式。

 

(2)用json.load()

 可以看到json.load()可以直接傳檔案對象,它會協助讀檔案,並且轉化為字典格式。

 3、寫入json檔案

同樣的,匯入json模組。可以用json.dumps()或者json.dump()將其轉化為json格式,寫入檔案。

(1)json.dumps()

首先用json.dumps()將字典轉化為json格式,存入user_info,然後將user_info寫入檔案。

其中,ensure_ascii=False 是為了保證中文不被編碼,能夠正常顯示。indent=4指的是縮排是4。

運行之後,user_info.json檔案內容為:

(2)json.dump()

json.dump()可以直接操作檔案對象,實現的功能一樣,能夠直接將字典格式轉化為json格式,並且寫入檔案。

4、小練習

學生資訊存在json檔案裡,要求實現學生的註冊和刪除。

stus_info.json檔案內容為為:

import jsondef op_data(filename,content=None):    if content:#如果有內容,將內容寫入json檔案        with open(filename,‘w‘,encoding=‘utf-8‘) as fw:            json.dump(content, fw, ensure_ascii=False, indent=4)    else:#如果content為None,則讀取json檔案        with open(filename,encoding=‘utf-8‘) as fr:            return json.load(fr)FILE_NAME = ‘stus_info.json‘#定義常量all_stus = op_data(FILE_NAME)for i in range(3):    choice = input(‘1註冊,2刪除,請輸入:‘)    if choice==‘1‘:        username = input(‘usenrame:‘)        pwd = input(‘pwd:‘)        if username not in all_stus:            all_stus[username]=pwd            op_data(FILE_NAME,all_stus)            print(‘恭喜,%s註冊成功!‘%username)    elif choice=="2":        username = input(‘usenrame:‘)        all_stus.pop(username)        op_data(FILE_NAME, all_stus)        print(‘%s刪除成功!‘%username)    else:        print(‘輸入錯誤,請重新輸入‘)

 

Python-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.