dump介紹
1 json
.作用:將python內置類型序列化為json對象后寫入文件
.參數:要存儲的數據以及可以用於存儲的文件對象
json.dump(number,file_object)
.樣例:把列表數據number儲存為json文件
import json
number = [1,2,3,4]
file_name = 'number.json'
with open(file_name,'w') as file_object:
json.dump(number,file_object)
注意
這里file_object傳遞的是一個指針
dumps
作用
將一個Python數據類型列表進行json格式的編碼(可以這么理解,json.dumps()函數是將字典轉化為字符串)
參數
json.dumps(dict)
樣例
將name列表轉為json對象
import json
number = [1,2,3,4]
number_json =json.dumps(number)
print(number_json)
print(type(number_json))
print(type(number))
結果
[1, 2, 3, 4]
<class 'str'>
<class 'list'>
load
作用
將字符形式的json數據轉為python類型
用於從json文件中讀取數據
常用的有轉化網頁請求之后的數據和直接讀取文件
參數
json.load(object)注意在讀取文件是,object也是一個指針
樣例
讀取網頁請求結果,在另一篇文章關於urllib.request和json入門級別理解中有提到,這里不贅述。
給一個讀取文件的例子
這里有個number.json文件,我對里面的內容進行改變,然后分析不同的結果
1、文件內容為:[1,2,3,4]
import json
print(json.load(open("number.json")))
print(type(json.load(open("number.json"))))
注意,一定是參數一定是open(),而不直接是文件名
[1, 2, 3, 4]
<class 'list'>
2、文件內容為:s=[1,2,3,4]
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
3、文件內容為:{"name": "zs", "age": 18}
{'name': 'zs', 'age': 18}
<class 'dict'>
自動識別類似字典類型,因此轉為字典,並且雙引號都別為了單引號
4、文件內容為:{'name': 'zs', 'age': 18}
報錯
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
總結
說明了在用json.load()方法時,它會自動對原數據進行分析,由於json只能由python基本數據類型轉變而成,所以如果原數據形式不符合python基本數據類型的樣式,那么將不會轉換成功。
loads
作用
把Json格式字符串解碼轉換成Python對象
參數
參數是數據內容,基本的數據類型的對象本身
還是從json.load()說起
import json
from urllib import request
url ='http://httpbin.org/ip'
resp = request.urlopen(url)
print(type(resp))
print(json.load(resp))
結果
<class 'http.client.HTTPResponse'>
{'origin': '113.57.182.250'}
即json.load()處理的是包含數據內容的數據文件對象
但是json.loads()處理的是數據對象本身
我們耐心點,對一個一個數據進行分析
1.如果我們對resp請求結果直接用json.loads()方法,而不是用json.load()
import json
from urllib import request
url ='http://httpbin.org/ip'
resp = request.urlopen(url)
print(type(resp))
print(json.loads(resp))
很顯然會報錯,因為resp不是可以基本的python數據類型
TypeError: the JSON object must be str, bytes or bytearray, not HTTPResponse
<class 'http.client.HTTPResponse'>
2.如果我們對resp.read()即文本內容來用json.loads()方法呢?
import json
from urllib import request
url ='http://httpbin.org/ip'
resp = request.urlopen(url)
print(type(resp))
print(json.loads(resp.read()))
那么會得到標准的結果,因為resp.read()是標准符合json樣式的字符串
<class 'http.client.HTTPResponse'>
{'origin': '113.57.182.250'}
這里用json.loads()對bytes類型的resp.read()也能轉換成功
但是這里出現了一個有意思的問題
import json
from urllib import request
url ='http://httpbin.org/ip'
resp = request.urlopen(url)
print(type(resp))
print(resp.read())
print(json.loads(resp.read()))
如果你在print(json.loads(resp.read())),有調用過resp.read(),那么再調用json.loads(resp.read())會出錯
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
這是什么原因我也不是很清楚,畢竟剛接觸而已,了解不深。
但是如果用變量的方法,可以避免這個問題
import json
from urllib import request
url ='http://httpbin.org/ip'
resp = request.