Python中json模塊load/loads方法實(shí)戰(zhàn)以及參數(shù)詳解
前言
適用于python2和python3
1. loads方法與load方法的異同
在Python中json是一個(gè)非常常用的模塊,這個(gè)主要有4個(gè)方法:
json.dumpsjson.dumpjson.loadsjson.load
這里主要分析講解一下json的loads和load方法。
這兩個(gè)方法中都是把其他類(lèi)型的對(duì)象轉(zhuǎn)為Python對(duì)象,這里先說(shuō)明一下Python對(duì)象,
Python對(duì)象包括:
所有Python基本數(shù)據(jù)類(lèi)型,列表,元組,字典,自己定義的類(lèi),等等等等,當(dāng)然不包括Python的字符串類(lèi)型,把字符串或者文件鎏中的字符串轉(zhuǎn)為字符串會(huì)報(bào)錯(cuò)的
1.1不相同點(diǎn):
loads操作的是字符串load操作的是文件流
1.2 相同點(diǎn)
- 除了第一個(gè)參數(shù)(要轉(zhuǎn)換的對(duì)象)類(lèi)型不同,其他所有的參數(shù)都相同
- 最終都是轉(zhuǎn)換成Python對(duì)象
1.3 例子
先來(lái)一個(gè)例子,除了要轉(zhuǎn)換的對(duì)象,其他什么參數(shù)都不傳:
s = '{"name": "wade", "age": 54, "gender": "man"}'
# json.loads讀取字符串并轉(zhuǎn)為Python對(duì)象
print("json.loads將字符串轉(zhuǎn)為Python對(duì)象: type(json.loads(s)) = {}".format(type(json.loads(s))))
print("json.loads將字符串轉(zhuǎn)為Python對(duì)象: json.loads(s) = {}".format(json.loads(s)))
# json.load讀取文件并將文件內(nèi)容轉(zhuǎn)為Python對(duì)象
# 數(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對(duì)象: type(json.load(f)) = {}".format(type(s1)))
print("json.load將文件內(nèi)容轉(zhuǎn)為Python對(duì)象: json.load(f) = {}".format(s1))
2. 轉(zhuǎn)換成Python對(duì)象
由于loads和load兩個(gè)方法只是處理的數(shù)據(jù)源不同,其他的參數(shù)都是相同的,返回的結(jié)果類(lèi)型也相同,故這是loads和load方法兩個(gè)只說(shuō)一個(gè),
日常工作中最常見(jiàn)的就是把字符串通過(guò)json.loads轉(zhuǎn)為字典,其實(shí)json的loads方法不僅可以把字符串轉(zhuǎn)為字典,還可以轉(zhuǎn)為任何Python對(duì)象。
比如說(shuō),轉(zhuǎn)成python基本數(shù)據(jù)類(lèi)型:
print('json.loads 將整數(shù)類(lèi)型的字符串轉(zhuǎn)為int類(lèi)型: type(json.loads("123456"))) --> {}'.format(type(json.loads("123456"))))
print('json.loads 將浮點(diǎn)類(lèi)型的字符串轉(zhuǎn)為float類(lèi)型: type(json.loads("123.456")) --> {}'.format(type(json.loads("123.456"))))
print('json.loads 將boolean類(lèi)型的字符串轉(zhuǎn)為bool類(lèi)型: type(json.loads("true")) --> {}'.format((type(json.loads("true")))))
print('json.loads 將列表類(lèi)型的字符串轉(zhuǎn)為列表: type(json.loads(\'["a", "b", "c"]\')) --> {}'.format(type(json.loads('["a", "b", "c"]'))))
print('json.loads 將字典類(lèi)型的字符串轉(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模塊會(huì)根據(jù)你的字符串自動(dòng)轉(zhuǎn)為最符合的數(shù)據(jù)類(lèi)型,但是需要注意的是不能把轉(zhuǎn)為字符串,否則會(huì)報(bào)json.decoder.JSONDecodeError錯(cuò)誤:
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 # 把一個(gè)字符串反序列化為Python對(duì)象,這個(gè)字符串可以是str類(lèi)型的,也可以是unicode類(lèi)型的
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding # 如果參數(shù)s是以ASCII編碼的字符串,那么需要手動(dòng)通過(guò)參數(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ù)是可選的,它會(huì)將(loads的)返回結(jié)果字典替換為你所指定的類(lèi)型
result of any object literal decode (a ``dict``). The return value of # 這個(gè)功能可以用來(lái)實(shí)現(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ù)是可選的,它會(huì)將結(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同時(shí)指定的話(huà)優(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ù)是可選的,它如果被指定的話(huà),在解碼json字符串的時(shí)候,
of every JSON float to be decoded. By default this is equivalent to # 符合float類(lèi)型的字符串將被轉(zhuǎn)為你所指定的,比如說(shuō)你可以指定為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ù)是可選的,它如果被指定的話(huà),在解碼json字符串的時(shí)候,
of every JSON int to be decoded. By default this is equivalent to # 符合int類(lèi)型的字符串將被轉(zhuǎn)為你所指定的,比如說(shuō)你可以指定為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ù)是可選的,它如果被指定的話(huà),在解碼json字符串的時(shí)候,
following strings: -Infinity, Infinity, NaN. # 如果出現(xiàn)以以下字符串: -Infinity, Infinity, NaN 那么指定的parse_constant方法將會(huì)被調(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ù)通過(guò)實(shí)現(xiàn)一個(gè)JSONDecoder的子類(lèi),來(lái)代替JSONDecoder,通過(guò)這個(gè)功能你可以自定義上面的那些parse_xxx參數(shù),這里就不舉例了
kwarg; otherwise ``JSONDecoder`` is used.
"""以下參數(shù)說(shuō)明是根據(jù)官方文檔翻譯的
3.1 s參數(shù)
把一個(gè)字符串反序列化為Python對(duì)象,這個(gè)字符串可以是str類(lèi)型的,也可以是unicode類(lèi)型的,如果參數(shù)s是以ASCII編碼的字符串,那么需要手動(dòng)通過(guò)參數(shù)encoding指定編碼方式,不是以ASCII編碼的字符串,是不被允許的,你必須把它轉(zhuǎn)為unicode
對(duì)于loads方法來(lái)說(shuō),s是一個(gè)字符串,而對(duì)于load方法來(lái)說(shuō),是一個(gè)數(shù)據(jù)流文件
3.2 object_hook參數(shù)
object_hook參數(shù)是可選的,它會(huì)將(loads的)返回結(jié)果字典替換為你所指定的類(lèi)型,這個(gè)功能可以用來(lái)實(shí)現(xiàn)自定義解碼器,如JSON-RPC
這里先定義一個(gè)Person對(duì)象:
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"}'
# 測(cè)試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對(duì)象了: --> " + str(isinstance(p, Person)))

3.3 object_pairs_hook參數(shù)
object_pairs_hook參數(shù)是可選的,它會(huì)將結(jié)果以key-value有序列表的形式返回,形式如:[(k1, v1), (k2, v2), (k3, v3)],如果object_hook和object_pairs_hook同時(shí)指定的話(huà)優(yōu)先返回object_pairs_hook
s = '{"name": "馬云", "age": 54, "gender": "man"}'
# 測(cè)試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 測(cè)試同時(shí)指定object_hook和object_pairs_hook,最終調(diào)用哪個(gè)參數(shù): --> " + str(type(p)))
print("json.loads 指定object_pairs_hook結(jié)果將會(huì)返回一個(gè)有序列表 --> {}".format(p))

3.4 parse_float參數(shù)
parse_float參數(shù)是可選的,它如果被指定的話(huà),在解碼json字符串的時(shí)候,符合float類(lèi)型的字符串將被轉(zhuǎn)為你所指定的,比如說(shuō)你可以指定為decimal.Decimal
# 測(cè)試json.loads方法的parse_float參數(shù)
print("-" * 30 + "> test parse_float <" + "-" * 30)
p = json.loads("123.456", parse_float=decimal.Decimal)
print("json.loads 通過(guò)parse_float參數(shù)將原本應(yīng)該轉(zhuǎn)為float類(lèi)型的字符串轉(zhuǎn)為decimal類(lèi)型: type(json.loads(\"123.456\", parse_float=decimal.Decimal)) --> " + str(type(p)))
print("")

3.5 parse_int參數(shù)
parse_int參數(shù)是可選的,它如果被指定的話(huà),在解碼json字符串的時(shí)候,符合int類(lèi)型的字符串將被轉(zhuǎn)為你所指定的,比如說(shuō)你可以指定為float
# 測(cè)試json.loads方法的parse_int參數(shù)
print("-" * 30 + "> test parse_int <" + "-" * 30)
p = json.loads("123", parse_int=float)
print("json.loads 通過(guò)parse_int參數(shù)將原本應(yīng)該轉(zhuǎn)為int類(lèi)型的字符串轉(zhuǎn)為float類(lèi)型: type(json.loads(\"123\", parse_int=float)) --> " + str(type(p)))

3.6 parse_constant參數(shù)
parse_constant參數(shù)是可選的,它如果被指定的話(huà),在解碼json字符串的時(shí)候,如果出現(xiàn)以以下字符串:-Infinity,Infinity,NaN那么指定的parse_constant方法將會(huì)被調(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ù)無(wú)窮大轉(zhuǎn)為一個(gè)非常小的數(shù)
elif "-Infinity" == s:
return -999999
# 將正無(wú)窮大轉(zhuǎn)為一個(gè)非常大的數(shù)
elif "Infinity" == s:
return 999999
else:
return s
# 測(cè)試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ù)
通過(guò)官方文檔的注釋我們可以知道json.load(s)方法具體的實(shí)現(xiàn)是通過(guò)JSONCoder類(lèi)實(shí)現(xiàn)的,而cls參數(shù)是用于自定義一個(gè)JSONCoder的子類(lèi),用于替換JSONCoder類(lèi),,通過(guò)這個(gè)功能你可以自定義上面的那些parse_xxx參數(shù),這里就不舉例了
總結(jié)
到此這篇關(guān)于Python中json模塊load/loads方法實(shí)戰(zhàn)以及參數(shù)詳解的文章就介紹到這了,更多相關(guān)Python json模塊load/loads方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
tensor和numpy的互相轉(zhuǎn)換的實(shí)現(xiàn)示例
這篇文章主要介紹了tensor和numpy的互相轉(zhuǎn)換的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Django中使用 Closure Table 儲(chǔ)存無(wú)限分級(jí)數(shù)據(jù)
對(duì)于數(shù)據(jù)量大的情況(比如用戶(hù)之間有邀請(qǐng)鏈,有點(diǎn)三級(jí)分銷(xiāo)的意思),就要用到 closure table 的結(jié)構(gòu)來(lái)進(jìn)行存儲(chǔ)。這篇文章主要介紹了Django中使用 Closure Table 儲(chǔ)存無(wú)限分級(jí)數(shù)據(jù),需要的朋友可以參考下2019-06-06
完美解決Pycharm無(wú)法導(dǎo)入包的問(wèn)題 Unresolved reference
今天小編就為大家分享一篇完美解決Pycharm無(wú)法導(dǎo)入包的問(wèn)題 Unresolved reference,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
基于Python批量鑲嵌拼接遙感影像/柵格數(shù)據(jù)(示例代碼)
這篇文章主要介紹了基于Python批量鑲嵌拼接遙感影像/柵格數(shù)據(jù),使用時(shí)直接修改Mosaic_GDAL函數(shù)的入?yún)⒕托辛?選擇數(shù)據(jù)存放的路徑會(huì)自動(dòng)拼接,命名也會(huì)自己設(shè)置無(wú)需額外修改,需要的朋友可以參考下2023-10-10
對(duì)python中GUI,Label和Button的實(shí)例詳解
今天小編就為大家分享一篇對(duì)python中GUI,Label和Button的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06
Django?分頁(yè)操作的實(shí)現(xiàn)示例
本文主要介紹了Django?分頁(yè)操作的實(shí)現(xiàn)示例,使用django.core.paginator.Paginator進(jìn)行實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2025-03-03

