python常用模組json

來源:互聯網
上載者:User

標籤:pen   sans   反序   bsp   資料轉換   其他   data   模組   報錯   

python jons模組

json模組 主要是解決資料格式的轉換問題,比如python接收到json對象需要轉換為python對象,供python處理,亦或者python資料需要發送到其給其他用戶端,這個時候需要把python資料轉換為json對象供其他用戶端操作。

json 提供4個方法,dumps loads dump load


dumps loads處理的都是字串對象

dump load 處理的是檔案對象

 

#1,將python對象轉換為json對象(序列化)
import jsondata = {"name":"cnblogs","url":"www.cnblogs.com"}new_data = json.dumps(data)print(new_data)print(type(new_data))

 





#python列錶轉換為json
data =[1,2,3]new_data = json.dumps(data)print(type(data))print(new_data)

 



#2,將json對象轉換為python處理的對象(還原序列化)


import json
#定一個json對象,這裡的必須要用引號,不然會報錯!

data = ‘‘‘{"name":"cnblogs","url":"www.cnblogs.com"}‘‘‘print(type(data))new_data = json.loads(data)print(new_data)print(type(new_data))

 


#3,dump 將python對象轉換為json對象,並寫入檔案

import jsondata = {"name":"cnblogs","url":"www.cnblogs.com"}with open(‘test.txt‘,‘w‘) as f:    json.dump(data,f)

 



#4,laod 從檔案裡面讀取並序列化成python對象
import jsonwith open(‘test.txt‘,‘r‘) as f:    data = json.load(f)print(data)print (type(data))

 

 

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.