詳解Python對JSON中的特殊類型進(jìn)行Encoder
Python 處理 JSON 數(shù)據(jù)時(shí),dumps 函數(shù)是經(jīng)常用到的,當(dāng) JSON 數(shù)據(jù)中有特殊類型時(shí),往往是比較頭疼的,因?yàn)榻?jīng)常會(huì)報(bào)這樣一個(gè)錯(cuò)誤。
自定義編碼類
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: wxnacy(wxnacy@gmail.com) import json from datetime import datetime USER_DATA = dict( id = 1, name = 'wxnacy', ts = datetime.now() ) print(json.dumps(USER_DATA))
Traceback (most recent call last): File "/Users/wxnacy/PycharmProjects/study/python/office_module/json_demo/dumps.py", line 74, in <module> dumps_encoder() File "/Users/wxnacy/PycharmProjects/study/python/office_module/json_demo/dumps.py", line 68, in dumps_encoder print(json.dumps(USER_DATA)) File "/Users/wxnacy/.pyenv/versions/3.6.0/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "/Users/wxnacy/.pyenv/versions/3.6.0/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/Users/wxnacy/.pyenv/versions/3.6.0/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/Users/wxnacy/.pyenv/versions/3.6.0/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type 'datetime' is not JSON serializable
原因在于 dumps 函數(shù)不知道如何處理 datetime 對象,默認(rèn)情況下 json 模塊使用 json.JSONEncoder 類來進(jìn)行編碼,此時(shí)我們需要自定義一下編碼類。
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: wxnacy(wxnacy@gmail.com) class CustomEncoder(json.JSONEncoder): def default(self, x): if isinstance(x, datetime): return int(x.timestamp()) return super().default(self, x)
定義編碼類 CustomEncoder 并重寫實(shí)例的 default 函數(shù),對特殊類型進(jìn)行處理,其余類型繼續(xù)使用父類的解析。
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: wxnacy(wxnacy@gmail.com) import json from datetime import datetime class CustomEncoder(json.JSONEncoder): def default(self, x): if isinstance(x, datetime): return int(x.timestamp()) return super().default(self, x) USER_DATA = dict( id = 1, name = 'wxnacy', ts = datetime.now() ) print(json.dumps(USER_DATA, cls=CustomEncoder)) # {"id": 1, "name": "wxnacy", "ts": 1562938926}
最后整合起來,將類使用 cls 參數(shù)傳入 dumps 函數(shù)即可。
使用 CustomEncoder 實(shí)例的 encode 函數(shù)可以對對象進(jìn)行轉(zhuǎn)碼
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: wxnacy(wxnacy@gmail.com) print(CustomEncoder().encode(datetime.now())) # 1562939035
在父類源碼中,所有的編碼邏輯都在 encode 函數(shù)中, default 只負(fù)責(zé)拋出 TypeError 異常,這就是文章開始報(bào)錯(cuò)的出處。
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: wxnacy(wxnacy@gmail.com) def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o) """ raise TypeError(f'Object of type {o.__class__.__name__} ' f'is not JSON serializable') def encode(self, o): """Return a JSON string representation of a Python data structure. >>> from json.encoder import JSONEncoder >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """ # This is for extremely simple cases and benchmarks. if isinstance(o, str): if self.ensure_ascii: return encode_basestring_ascii(o) else: return encode_basestring(o) # This doesn't pass the iterator directly to ''.join() because the # exceptions aren't as detailed. The list call should be roughly # equivalent to the PySequence_Fast that ''.join() would do. chunks = self.iterencode(o, _one_shot=True) if not isinstance(chunks, (list, tuple)): chunks = list(chunks) return ''.join(chunks)
單分派裝飾器處理對象
CustomEncoder 如果處理的對象種類很多的話,需要寫多個(gè) if elif else 來區(qū)分,這樣并不是不行,但是不夠優(yōu)雅,不夠 pythonic
根據(jù)對象的類型不同,而做出不同的處理。剛好有個(gè)裝飾器可以做到這點(diǎn),它就是單分派函數(shù) functools.singledispatch
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: wxnacy(wxnacy@gmail.com) from datetime import datetime from datetime import date from functools import singledispatch class CustomEncoder(json.JSONEncoder): def default(self, x): try: return encode(x) except TypeError: return super().default(self, x) @singledispatch # 1 def encode(x): raise TypeError('Unencode type') @encode.register(datetime) # 2 def _(x): return int(x.timestamp()) @encode.register(date) def _(x): return x.isoformat() print(json.dumps(dict(dt = datetime.now(), d = date.today()), cls=CustomEncoder)) # {"dt": 1562940781, "d": "2019-07-12"}
1 使用 @singledispatch 裝飾 encode 函數(shù),是他處理默認(rèn)類型。同時(shí)給他添加一個(gè)裝飾器構(gòu)造函數(shù)變量。
2 `@encode.register () 是一個(gè)裝飾器構(gòu)造函數(shù),接收需要處理的對象類型作為參數(shù)。用它裝飾的函數(shù)不需要名字, _` 代替即可。
最后提一點(diǎn), json 也可以在命令行中使用
$ echo '{"json": "obj"}' | python -m json.tool { "json": "obj" }
參考鏈接
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python實(shí)現(xiàn)JSON反序列化類對象的示例
- Python如何把不同類型數(shù)據(jù)的json序列化
- Python爬蟲數(shù)據(jù)的分類及json數(shù)據(jù)使用小結(jié)
- Python xml、字典、json、類四種數(shù)據(jù)類型如何實(shí)現(xiàn)互相轉(zhuǎn)換
- Python 之 Json序列化嵌套類方式
- python聚類算法解決方案(rest接口/mpp數(shù)據(jù)庫/json數(shù)據(jù)/下載圖片及數(shù)據(jù))
- 把JSON數(shù)據(jù)格式轉(zhuǎn)換為Python的類對象方法詳解(兩種方法)
- 在Python?中將類對象序列化為JSON
相關(guān)文章
Django用戶登錄與注冊系統(tǒng)的實(shí)現(xiàn)示例
這篇文章主要介紹了Django用戶登錄與注冊系統(tǒng)的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06深入理解Python虛擬機(jī)中的Code?obejct
在本篇文章當(dāng)中主要給大家深入介紹在?cpython?當(dāng)中非常重要的一個(gè)數(shù)據(jù)結(jié)構(gòu)?code?object!?我們簡單介紹了一下在?code?object?當(dāng)中有哪些字段以及這些字段的簡單含義,在本篇文章當(dāng)中將會(huì)舉一些例子以便更加深入理解這些字段2023-04-04python3使用python-redis-lock解決并發(fā)計(jì)算問題
本文主要介紹了python3使用python-redis-lock解決并發(fā)計(jì)算問題,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10Python爬取十篇新聞統(tǒng)計(jì)TF-IDF
這篇文章主要為大家詳細(xì)介紹了Python爬取十篇新聞統(tǒng)計(jì)TF-IDF的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01使用python 計(jì)算百分位數(shù)實(shí)現(xiàn)數(shù)據(jù)分箱代碼
這篇文章主要介紹了使用python 計(jì)算百分位數(shù)實(shí)現(xiàn)數(shù)據(jù)分箱代碼,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03python3+PyQt5實(shí)現(xiàn)拖放功能
這篇文章主要為大家詳細(xì)介紹了python3+PyQt5實(shí)現(xiàn)拖放功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04Python中識別圖片/滑塊驗(yàn)證碼準(zhǔn)確率極高的ddddocr庫詳解
驗(yàn)證碼的種類有很多,它是常用的一種反爬手段,包括:圖片驗(yàn)證碼,滑塊驗(yàn)證碼,等一些常見的驗(yàn)證碼場景。這里推薦一個(gè)簡單實(shí)用的識別驗(yàn)證碼的庫?ddddocr?(帶帶弟弟ocr)庫,希望大家喜歡2023-02-02python接口自動(dòng)化(十七)--Json 數(shù)據(jù)處理---一次爬坑記(詳解)
這篇文章主要介紹了python Json 數(shù)據(jù)處理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04