Amaze UI Logo

码动指尖



python3对象转字典(dict)小记

python3对象转字典(dict)其实是个神奇的事情,对于json.dumps这个函数,也是有很多参数可供选择的,如果你有兴趣读一读源码便可知了。

这里贴上dumps的定义源码和相应注释,有兴趣的同学可以读一读。我这里只解读default参数。

def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
       allow_nan=True, cls=None, indent=None, separators=None,
       default=None, sort_keys=False, **kw):
"""Serialize ``obj`` to a JSON formatted ``str``.

   If ``skipkeys`` is true then ``dict`` keys that are not basic types
   (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
   instead of raising a ``TypeError``.

   If ``ensure_ascii`` is false, then the return value can contain non-ASCII
   characters if they appear in strings contained in ``obj``. Otherwise, all
   such characters are escaped in JSON strings.

   If ``check_circular`` is false, then the circular reference check
   for container types will be skipped and a circular reference will
   result in an ``OverflowError`` (or worse).

   If ``allow_nan`` is false, then it will be a ``ValueError`` to
   serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
   strict compliance of the JSON specification, instead of using the
   JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).

   If ``indent`` is a non-negative integer, then JSON array elements and
   object members will be pretty-printed with that indent level. An indent
   level of 0 will only insert newlines. ``None`` is the most compact
   representation.

   If specified, ``separators`` should be an ``(item_separator, key_separator)``
   tuple.  The default is ``(', ', ': ')`` if *indent* is ``None`` and
   ``(',', ': ')`` otherwise.  To get the most compact JSON representation,
   you should specify ``(',', ':')`` to eliminate whitespace.

   ``default(obj)`` is a function that should return a serializable version
   of obj or raise TypeError. The default simply raises TypeError.

   If *sort_keys* is true (default: ``False``), then the output of
   dictionaries will be sorted by key.

   To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
   ``.default()`` method to serialize additional types), specify it with
   the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.

   """


这里单独提出default 的注释

``default(obj)`` is a function that should return a serializable version
   of obj or raise TypeError. The default simply raises TypeError.


可以很清楚的读出来,default本身是一个函数,会返回一个对象的可序列化版本或者抛出类型异常,正常情况默认抛出TypeError的异常,那么问题来了,default的实现呢,其实我们这样读了源码之后,还是会有很大的困惑,具体用法,就直接default=我们定义的函数吗?

这样只是会用了,实际上并没有解决内在的问题(本质),会用很简单,但是我们应该知其根本,如果是赶项目那可以不用去深究,但是如果是学习,我认为这是最重要的。


接下来继续看代码,这里就是dumps的实现代码了。


# cached encoder
if (not skipkeys and ensure_ascii and
   check_circular and allow_nan and
   cls is None and indent is None and separators is None and
   default is None and not sort_keys and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
   check_circular=check_circular, allow_nan=allow_nan, indent=indent,
   separators=separators, default=default, sort_keys=sort_keys,
   **kw).encode(obj)


可以从代码中看出来,如果传入了default,将会返回cls(...)这个函数

那么cls在哪里,可以看到  在没有传入cls的情况下, cls = JSONEncoder


接下来跳到JSONEncoder


def __init__(self, *, skipkeys=False, ensure_ascii=True,
       check_circular=True, allow_nan=True, sort_keys=False,
       indent=None, separators=None, default=None):


default被传给了JSONEncoder的default

这下就认真看一下它的default了。

这是default 的解释


If specified, default is a function that gets called for objects
that can't otherwise be serialized.  It should return a JSON encodable
version of the object or raise a ``TypeError``.


简单来说,这段注释的意思就是default如果传入了就是一个会被对象调用的函数,并返回一个可以被json化的对象或者抛出类型异常(TypeError)。

继续看源码


if default is not None:
self.default = default


如果传入了default,这个default就将会被传给JSONEncoder类的default

JSONEncoder类的default实现如下

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("Object of type '%s' is not JSON serializable" %
o.__class__.__name__)


注释已经给的很清楚了,让我们在实现的时候,返回一个o的可序列化对象就行了,所以,很明显我们在定义传入函数的时候,返回o的可序列化对象即可。

这里是最简单的实现,利用到了匿名函数 lambda

data = json.dumps(data, default=lambda o: o.__dict__)

如此便可将传入数据里的对象的属性提取出来,实际上是用到了类的__dict__方法,这样针对大多数情况是完全可行了的。如果需求不是特别例外,则这样完全够用了。


接下来就是特殊情况的处理方法。

比如sqlalchemy的db.Model对象,这个对象传入上述方法,则会报错

TypeError: Object of type 'InstanceState' is not JSON serializable

这个错误的含义正如输出一样,类型错误,传入对象不可被序列化。


于是上述方法便失效了。那么我们就应该思考其他方法,经过几番思考和查阅,我决定自己写一个函数来进行转化。实现代码如下:

@staticmethod
def object_to_dict(value):
data = {}
for column in value.__table__.columns:
data[column.name] = getattr(value, column.name)
return data


如此通过__table__取得对应的属性列表,然后将其转入到新创建的字典,最后返回即可。

__table__这个属性,将会在接下来进行详细的介绍,敬请期待。


希望这篇小文对你有用,谢谢支持,如有错误欢迎留言。

 Python

作者  :  奕弈

喵喵喵,你在心上



评论


About ME

about me

奕弈

为了最初的心,努力奋斗,从不懈怠的学习。

我不想成为一个庸俗的人。十年百年后,当我们死去,质疑我们的人同样死去,后人看到的是裹足不前、原地打转的你,还是一直奔跑、走到远方的我?

Contact ME