Python中json模塊load/loads方法實戰(zhàn)以及參數(shù)詳解
前言
適用于python2和python3
1. loads方法與load方法的異同
在Python中json是一個非常常用的模塊,這個主要有4個方法:
json.dumps
json.dump
json.loads
json.load
這里主要分析講解一下json的loads
和load
方法。
這兩個方法中都是把其他類型的對象轉(zhuǎn)為Python對象,這里先說明一下Python對象,
Python對象包括:
所有Python基本數(shù)據(jù)類型,列表,元組,字典,自己定義的類,等等等等,當(dāng)然不包括Python的字符串類型,把字符串或者文件鎏中的字符串轉(zhuǎn)為字符串會報錯的
1.1不相同點:
loads
操作的是字符串load
操作的是文件流
1.2 相同點
- 除了第一個參數(shù)(要轉(zhuǎn)換的對象)類型不同,其他所有的參數(shù)都相同
- 最終都是轉(zhuǎn)換成Python對象
1.3 例子
先來一個例子,除了要轉(zhuǎn)換的對象,其他什么參數(shù)都不傳:
s = '{"name": "wade", "age": 54, "gender": "man"}' # json.loads讀取字符串并轉(zhuǎn)為Python對象 print("json.loads將字符串轉(zhuǎn)為Python對象: type(json.loads(s)) = {}".format(type(json.loads(s)))) print("json.loads將字符串轉(zhuǎn)為Python對象: json.loads(s) = {}".format(json.loads(s))) # json.load讀取文件并將文件內(nèi)容轉(zhuǎn)為Python對象 # 數(shù)據(jù)文件要s.json的內(nèi)容 --> {"name": "wade", "age": 54, "gender": "man"} with open('s.json', 'r') as f: s1 = json.load(f) print("json.load將文件內(nèi)容轉(zhuǎn)為Python對象: type(json.load(f)) = {}".format(type(s1))) print("json.load將文件內(nèi)容轉(zhuǎn)為Python對象: json.load(f) = {}".format(s1))
2. 轉(zhuǎn)換成Python對象
由于loads
和load
兩個方法只是處理的數(shù)據(jù)源不同,其他的參數(shù)都是相同的,返回的結(jié)果類型也相同,故這是loads
和load
方法兩個只說一個,
日常工作中最常見的就是把字符串通過json.loads
轉(zhuǎn)為字典,其實json的loads
方法不僅可以把字符串轉(zhuǎn)為字典,還可以轉(zhuǎn)為任何Python對象。
比如說,轉(zhuǎn)成python
基本數(shù)據(jù)類型:
print('json.loads 將整數(shù)類型的字符串轉(zhuǎn)為int類型: type(json.loads("123456"))) --> {}'.format(type(json.loads("123456")))) print('json.loads 將浮點類型的字符串轉(zhuǎn)為float類型: type(json.loads("123.456")) --> {}'.format(type(json.loads("123.456")))) print('json.loads 將boolean類型的字符串轉(zhuǎn)為bool類型: type(json.loads("true")) --> {}'.format((type(json.loads("true"))))) print('json.loads 將列表類型的字符串轉(zhuǎn)為列表: type(json.loads(\'["a", "b", "c"]\')) --> {}'.format(type(json.loads('["a", "b", "c"]')))) print('json.loads 將字典類型的字符串轉(zhuǎn)為字典: type(json.loads(\'{"a": 1, "b": 1.2, "c": true, "d": "ddd"}\')) --> %s' % str(type(json.loads('{"a": 1, "b": 1.2, "c": true, "d": "ddd"}'))))
json模塊會根據(jù)你的字符串自動轉(zhuǎn)為最符合的數(shù)據(jù)類型,但是需要注意的是不能把轉(zhuǎn)為字符串,否則會報json.decoder.JSONDecodeError
錯誤:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
3. json.load(s)的參數(shù)
我們先看下json.loads方法的簽名:
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON # 把一個字符串反序列化為Python對象,這個字符串可以是str類型的,也可以是unicode類型的 document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding # 如果參數(shù)s是以ASCII編碼的字符串,那么需要手動通過參數(shù)encoding指定編碼方式, other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name # 不是以ASCII編碼的字符串,是不被允許的,你必須把它轉(zhuǎn)為unicode must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ``object_hook`` is an optional function that will be called with the # object_hook參數(shù)是可選的,它會將(loads的)返回結(jié)果字典替換為你所指定的類型 result of any object literal decode (a ``dict``). The return value of # 這個功能可以用來實現(xiàn)自定義解碼器,如JSON-RPC ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``object_pairs_hook`` is an optional function that will be called with the # object_pairs_hook參數(shù)是可選的,它會將結(jié)果以key-value列表的形式返回 result of any object literal decoded with an ordered list of pairs. The # 形式如:[(k1, v1), (k2, v2), (k3, v3)] return value of ``object_pairs_hook`` will be used instead of the ``dict``. # 如果object_hook和object_pairs_hook同時指定的話優(yōu)先返回object_pairs_hook This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict will remember the order of insertion). If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. ``parse_float``, if specified, will be called with the string # parse_float參數(shù)是可選的,它如果被指定的話,在解碼json字符串的時候, of every JSON float to be decoded. By default this is equivalent to # 符合float類型的字符串將被轉(zhuǎn)為你所指定的,比如說你可以指定為decimal.Decimal float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string # parse_int參數(shù)是可選的,它如果被指定的話,在解碼json字符串的時候, of every JSON int to be decoded. By default this is equivalent to # 符合int類型的字符串將被轉(zhuǎn)為你所指定的,比如說你可以指定為float int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the # parse_constant參數(shù)是可選的,它如果被指定的話,在解碼json字符串的時候, following strings: -Infinity, Infinity, NaN. # 如果出現(xiàn)以以下字符串: -Infinity, Infinity, NaN 那么指定的parse_constant方法將會被調(diào)用到 This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` # 你也可以用cls參數(shù)通過實現(xiàn)一個JSONDecoder的子類,來代替JSONDecoder,通過這個功能你可以自定義上面的那些parse_xxx參數(shù),這里就不舉例了 kwarg; otherwise ``JSONDecoder`` is used. """
以下參數(shù)說明是根據(jù)官方文檔翻譯的
3.1 s參數(shù)
把一個字符串反序列化為Python對象,這個字符串可以是str類型的,也可以是unicode
類型的,如果參數(shù)s
是以ASCII
編碼的字符串,那么需要手動通過參數(shù)encoding
指定編碼方式,不是以ASCII
編碼的字符串,是不被允許的,你必須把它轉(zhuǎn)為unicode
對于loads
方法來說,s是一個字符串,而對于load
方法來說,是一個數(shù)據(jù)流文件
3.2 object_hook參數(shù)
object_hook
參數(shù)是可選的,它會將(loads的)返回結(jié)果字典替換為你所指定的類型,這個功能可以用來實現(xiàn)自定義解碼器,如JSON-RPC
這里先定義一個Person
對象:
class Person: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def toJSON(self): return { "name": self.name, "age": self.age, "gender": self.gender } @staticmethod def parseJSON(dct): if isinstance(dct, dict): p = Person(dct["name"], int(dct['age']), dct['gender']) return p return dct
OK,試下object_hook
參數(shù)吧:
s = '{"name": "馬云", "age": 54, "gender": "man"}' # 測試json.loads方法的object_hook參數(shù) p = json.loads(s, object_hook=Person.parseJSON) print("json.loads 是否將字符串轉(zhuǎn)為字典了: --> " + str(isinstance(p, dict))) print("json.loads 是否將字符串轉(zhuǎn)為Person對象了: --> " + str(isinstance(p, Person)))
3.3 object_pairs_hook參數(shù)
object_pairs_hook
參數(shù)是可選的,它會將結(jié)果以key-value有序列表的形式返回,形式如:[(k1, v1), (k2, v2), (k3, v3)]
,如果object_hook
和object_pairs_hook
同時指定的話優(yōu)先返回object_pairs_hook
s = '{"name": "馬云", "age": 54, "gender": "man"}' # 測試json.loads方法的object_pairs_hook參數(shù) print("-" * 30 + "> test object_pairs_hook <" + "-" * 30) p = json.loads(s, object_hook=Person.parseJSON, object_pairs_hook=collections.OrderedDict) # p = json.loads(s, object_hook=Person.parseJSON, object_pairs_hook=Person.parseJSON) print("json.loads 測試同時指定object_hook和object_pairs_hook,最終調(diào)用哪個參數(shù): --> " + str(type(p))) print("json.loads 指定object_pairs_hook結(jié)果將會返回一個有序列表 --> {}".format(p))
3.4 parse_float參數(shù)
parse_float
參數(shù)是可選的,它如果被指定的話,在解碼json
字符串的時候,符合float
類型的字符串將被轉(zhuǎn)為你所指定的,比如說你可以指定為decimal.Decimal
# 測試json.loads方法的parse_float參數(shù) print("-" * 30 + "> test parse_float <" + "-" * 30) p = json.loads("123.456", parse_float=decimal.Decimal) print("json.loads 通過parse_float參數(shù)將原本應(yīng)該轉(zhuǎn)為float類型的字符串轉(zhuǎn)為decimal類型: type(json.loads(\"123.456\", parse_float=decimal.Decimal)) --> " + str(type(p))) print("")
3.5 parse_int參數(shù)
parse_int
參數(shù)是可選的,它如果被指定的話,在解碼json
字符串的時候,符合int
類型的字符串將被轉(zhuǎn)為你所指定的,比如說你可以指定為float
# 測試json.loads方法的parse_int參數(shù) print("-" * 30 + "> test parse_int <" + "-" * 30) p = json.loads("123", parse_int=float) print("json.loads 通過parse_int參數(shù)將原本應(yīng)該轉(zhuǎn)為int類型的字符串轉(zhuǎn)為float類型: type(json.loads(\"123\", parse_int=float)) --> " + str(type(p)))
3.6 parse_constant參數(shù)
parse_constant
參數(shù)是可選的,它如果被指定的話,在解碼json
字符串的時候,如果出現(xiàn)以以下字符串:-Infinity
,Infinity
,NaN
那么指定的parse_constant
方法將會被調(diào)用到
def transform(s): """ 此方法作為參數(shù)傳給json.load(s)方法的parse_轉(zhuǎn)譯NAN, -Infinity,Infinity :param s: :return: """ # NaN --> not a number if "NaN" == s: return "Not a Number" # 將負(fù)無窮大轉(zhuǎn)為一個非常小的數(shù) elif "-Infinity" == s: return -999999 # 將正無窮大轉(zhuǎn)為一個非常大的數(shù) elif "Infinity" == s: return 999999 else: return s # 測試json.loads方法的parse_constant參數(shù) print("-" * 30 + "> test parse_constant <" + "-" * 30) print("json.loads Infinity: --> " + str(json.loads('Infinity'))) print("json.loads parse_constant convert Infinity: --> " + str(json.loads('Infinity', parse_constant=transform_constant))) print("json.loads -Infinity: --> " + str(json.loads('-Infinity'))) print("json.loads parse_constant convert -Infinity: --> " + str(json.loads('-Infinity', parse_constant=transform_constant))) print("json.loads NaN: --> " + str(json.loads('NaN'))) print("json.loads parse_constant convert NaN : --> " + str(json.loads('NaN', parse_constant=transform_constant))) print("")
3.7 cls參數(shù)
通過官方文檔的注釋我們可以知道json.load(s)
方法具體的實現(xiàn)是通過JSONCoder
類實現(xiàn)的,而cls
參數(shù)是用于自定義一個JSONCoder
的子類,用于替換JSONCoder
類,,通過這個功能你可以自定義上面的那些parse_xxx參數(shù),這里就不舉例了
總結(jié)
到此這篇關(guān)于Python中json模塊load/loads方法實戰(zhàn)以及參數(shù)詳解的文章就介紹到這了,更多相關(guān)Python json模塊load/loads方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python中的accumulate()函數(shù)示例詳解
accumulate 函數(shù)是Python標(biāo)準(zhǔn)庫 itertools 模塊中的一個函數(shù),用于生成累積計算的結(jié)果,這篇文章主要介紹了python中的accumulate()函數(shù),需要的朋友可以參考下2023-09-09Python中使用logging模塊代替print(logging簡明指南)
這篇文章主要介紹了Python中使用logging模塊代替print的好處說明,主旨是logging模塊簡明指南,logging模塊的使用方法介紹,需要的朋友可以參考下2014-07-07Pandas之?dāng)?shù)據(jù)追加df.append方式
這篇文章主要介紹了Pandas之?dāng)?shù)據(jù)追加df.append方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08python3中apply函數(shù)和lambda函數(shù)的使用詳解
本文主要介紹了python3中apply函數(shù)和lambda函數(shù)的使用詳解,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02Python采集大學(xué)教務(wù)系統(tǒng)成績單實戰(zhàn)示例
這篇文章主要為大家介紹了Python采集大學(xué)教務(wù)系統(tǒng)成績單實戰(zhàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04用于ETL的Python數(shù)據(jù)轉(zhuǎn)換工具詳解
這篇文章主要介紹了用于ETL的Python數(shù)據(jù)轉(zhuǎn)換工具,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07Python網(wǎng)絡(luò)請求模塊urllib與requests使用介紹
網(wǎng)絡(luò)爬蟲的第一步就是根據(jù)URL,獲取網(wǎng)頁的HTML信息。在Python3中,可以使用urllib和requests進(jìn)行網(wǎng)頁數(shù)據(jù)獲取,這篇文章主要介紹了Python網(wǎng)絡(luò)請求模塊urllib與requests使用2022-10-10