欧美成人午夜免费全部完,亚洲午夜福利精品久久,а√最新版在线天堂,另类亚洲综合区图片小说区,亚洲欧美日韩精品色xxx

千鋒扣丁學(xué)堂Python培訓(xùn)之詳解JSON中特殊類型進行Encoder

2019-07-15 13:29:45 2442瀏覽

今天千鋒扣丁學(xué)堂Python培訓(xùn)老師給大家分享一篇關(guān)于詳解Python對JSON中的特殊類型進行Encoder,文中通過示例代碼介紹的非常詳細,首先Python處理JSON數(shù)據(jù)時,dumps函數(shù)是經(jīng)常用到的,當(dāng)JSON數(shù)據(jù)中有特殊類型時,往往是比較頭疼的,因為經(jīng)常會報這樣一個錯誤。



自定義編碼類

#!/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對象,默認情況下json模塊使用json.JSONEncoder類來進行編碼,此時我們需要自定義一下編碼類。

#!/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并重寫實例的default函數(shù),對特殊類型進行處理,其余類型繼續(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實例的encode函數(shù)可以對對象進行轉(zhuǎn)碼

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
print(CustomEncoder().encode(datetime.now()))
# 1562939035

在父類源碼中,所有的編碼邏輯都在encode函數(shù)中,default只負責(zé)拋出TypeError異常,這就是文章開始報錯的出處。

#!/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如果處理的對象種類很多的話,需要寫多個ifelifelse來區(qū)分,這樣并不是不行,但是不夠優(yōu)雅,不夠pythonic

根據(jù)對象的類型不同,而做出不同的處理。剛好有個裝飾器可以做到這點,它就是單分派函數(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ù),是他處理默認類型。同時給他添加一個裝飾器構(gòu)造函數(shù)變量。

2、`@encode.register()是一個裝飾器構(gòu)造函數(shù),接收需要處理的對象類型作為參數(shù)。用它裝飾的函數(shù)不需要名字,_`代替即可。

最后提一點,json也可以在命令行中使用

$ echo '{"json": "obj"}' | python -m json.tool
{
  "json": "obj"
}

以上就是關(guān)于千鋒扣丁學(xué)堂Python培訓(xùn)之詳解JSON中特殊類型進行Encoder的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,最后想要了解更多關(guān)于Python和人工智能方面內(nèi)容的小伙伴,請關(guān)注扣丁學(xué)堂Python培訓(xùn)官網(wǎng)、微信等平臺,扣丁學(xué)堂IT職業(yè)在線學(xué)習(xí)教育平臺為您提供權(quán)威的Python開發(fā)環(huán)境搭建視頻,Python培訓(xùn)后的前景無限,行業(yè)薪資和未來的發(fā)展會越來越好的,扣丁學(xué)堂老師精心推出的Python視頻教程定能讓你快速掌握Python從入門到精通開發(fā)實戰(zhàn)技能??鄱W(xué)堂Python技術(shù)交流群:279521237。


扣丁學(xué)堂微信公眾號                          Python全棧開發(fā)爬蟲人工智能機器學(xué)習(xí)數(shù)據(jù)分析免費公開課直播間


      【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】         【掃碼進入Python全棧開發(fā)免費公開課】



查看更多關(guān)于"Python開發(fā)資訊"的相關(guān)文章>

標(biāo)簽: Python培訓(xùn) Python視頻教程 Python在線視頻 Python學(xué)習(xí)視頻 Python培訓(xùn)班

熱門專區(qū)

暫無熱門資訊

課程推薦

微信
微博
15311698296

全國免費咨詢熱線

郵箱:codingke@1000phone.com

官方群:148715490

北京千鋒互聯(lián)科技有限公司版權(quán)所有   北京市海淀區(qū)寶盛北里西區(qū)28號中關(guān)村智誠科創(chuàng)大廈4層
京ICP備2021002079號-2   Copyright ? 2017 - 2022
返回頂部 返回頂部