python的json模組的dumps,loads,dump,load方法介紹

來源:互聯網
上載者:User

標籤:item   request   highlight   通過   filename   address   img   color   inf   

 
#Auther Bob
#--*--conding:utf-8 --*--

#jshon這個模組就是做序列化處理的,主要用到json模組的四種方法

#1、dumps
#2、loads
#3、dump
#4、load

#先介紹dumps方法
#通過jshon的dumps的模組可以把特定的對象序列化處理為字串
# import json


# l1 = [1,2,3,454]
# d1 = {‘k1‘:‘v1‘}
# ret = json.dumps(l1)
# print(type(ret))
# ret = json.dumps(d1)
# print(type(ret))


# <class ‘str‘>
# <class ‘str‘>


# l1 = ‘[1,2,3,4]‘
# d1 = ‘{"k1":"v1"}‘
# print(type(l1))
# print(type(d1))

#在來介紹loads方法
#上面的l1和d1都是字串,但是他們的外形和list和dict一樣,我們就可以通過還原序列化把這2個字串轉換成list和dict,這裡如果
#外形不是list或者dict的形狀,則不會轉換成功的,這裡必須要注意,字串的外面的引號必須是“單引號”,內部必須是雙引號,如果不是這樣,json模組會報錯的
# ret = json.loads(l1)
# print(ret,type(ret))
# ret = json.loads(d1)
# print(ret,type(ret))


# [1, 2, 3, 4] <class ‘list‘>
# {‘k1‘: ‘v1‘} <class ‘dict‘>




#來做一個小練習,通過第三方模組get到http請求,然後json模組把返回的字串結構的資料轉換字典的形式,這樣我們就可以
#對這個字典做操作
# import requests
# import json
#
# ret = requests.get(‘http://wthrcdn.etouch.cn/weather_mini?city=北京‘)
# ret.encoding = ‘utf-8‘
# s1 = ret.text
# print(s1,type(s1))

#拿到字串形式的資料
# {"desc":"invilad-citykey","status":1002} <class ‘str‘>
#
# d1 = json.loads(s1)
# print(d1,type(d1))

#通過loads的方法,把字串轉換成字典
# {‘desc‘: ‘invilad-citykey‘, ‘status‘: 1002} <class ‘dict‘>

#上面的dumps和loads方法都在記憶體中轉換,下面的dump和load的方法會多一個步驟,dump是把序列化後的字串寫到一個檔案中,而
#load是從一個一個檔案中讀取檔案

#然後來介紹dump方法
# import json
# d1 = {‘name‘:‘foot‘}
#這一步就會把d1做序列化處理後的字串寫到db這個檔案中

# json.dump(d1,open(‘db‘,‘w‘))
# d1 = json.load(open(‘db‘,‘r‘))
# print(d1,type(d1))

# {‘name‘: ‘foot‘} <class ‘dict‘>


今天又學習了shelve這個模組,這個模組用起來還是很簡單的
import shelvef = shelve.open("shelve_test")f[‘info‘] = "alex"f["age"] = [1,34,5,6,33,44]f["name"] = {"name":"alex","add":"sz"}f.close()f = shelve.open("shelve_test")# 這裡這個f我們就可以理解為是一個字典對象,所以shelve儲存資料就按照字典的方式儲存資料print(f.get("info"))print(f.get("age"))print(f.get("name"))print(f[‘info‘])print(f.values())print(f.items())print(f.keys())

 

結果如下

1234567 alex[1, 34, 5, 6, 33, 44]{‘name‘: ‘alex‘, ‘add‘: ‘sz‘}alexValuesView(<shelve.DbfilenameShelf object at 0x019EB250>)ItemsView(<shelve.DbfilenameShelf object at 0x019EB250>)KeysView(<shelve.DbfilenameShelf object at 0x019EB250>)

  

shelve也可以用with的方式開啟
123456789101112131415161718192021 import shelvewith shelve.open("test_shelve.db") as f:    f["k1"] = {        "name":"zhangguojun1",        "age":12,        "address":"shenzhen1"    }    f["k2"] = {        "name":"zhangguojun2",        "age":12,        "address":"shenzhen2"    }    f["k3"] = {        "name":"zhangguojun3",        "age":12,        "address":"shenzhen3"    }    f["k4"] = ["張國軍1","張國軍2","張國軍3"]with shelve.open("test_shelve.db") as f:    print(f["k1"]["name"])    print(f["k4"][0])

  

結果如下

12 zhangguojun1張國軍1

  

123456789 with shelve.open("shelve.ini","w") as f:    f["k1"] = test_list    f["k2"] = test_dict    f["k3"] = s with shelve.open("shelve.ini","r") as f:    print(f["k3"])    print(f["k2"])    print(f["k1"])

python的json模組的dumps,loads,dump,load方法介紹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.