JSON usage in Python

与世无争的帅哥 提交于 2019-12-06 15:29:22

Take a look at load() and dump(); each accept an object_hook function to decode and encode objects not ordinarily JSONable. Maybe this will do for you.

The following snipped of code illustrates several aspects of working with JSON in Python 3. Take note of the JSONEncoder class and the implementation of encoding decimal and datetime.

import json
from decimal import Decimal
from datetime import datetime, date

class JSONEncoder(json.JSONEncoder):
  def default(self, o):
    if isinstance(o, Decimal):
      return float(o)
    elif isinstance(o, (datetime, date)):
      return o.isoformat()
    return super().default(self,o)

class JSONDecoder(json.JSONDecoder):
  pass

_Default_Encoder = JSONEncoder(
  skipkeys=False,
  ensure_ascii=False,
  check_circular=True,
  allow_nan=True,
  indent=None,
  separators=None,
  default=None,
  )

_Default_Decoder = JSONDecoder(
  object_hook=None, 
  object_pairs_hook=None
  )

Encode = _Default_Encoder.encode
Decode = _Default_Decoder.decode
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!