栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 自定义JSON Encoder

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 自定义JSON Encoder

如果用 json.dumps 一个自定义的类,json自带的编码器是无法解析的

import json
class A:
    def __init__(self, a):
        self.a = a
    def __repr__(self):
        return str(self.a)

foo = {'a': 666, 'b': A(666)}
json.dumps(foo)

报错如下

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
      7 
      8 foo = {'a': 666, 'b': A(666)}
----> 9 json.dumps(foo)

D:ProgramFilesNoSpaceMiniconda3envspy36libjson__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    229         cls is None and indent is None and separators is None and
    230         default is None and not sort_keys and not kw):
--> 231         return _default_encoder.encode(obj)
    232     if cls is None:
    233         cls = JSonEncoder

D:ProgramFilesNoSpaceMiniconda3envspy36libjsonencoder.py in encode(self, o)
    197         # exceptions aren't as detailed.  The list call should be roughly
    198         # equivalent to the PySequence_Fast that ''.join() would do.
--> 199         chunks = self.iterencode(o, _one_shot=True)
    200         if not isinstance(chunks, (list, tuple)):
    201             chunks = list(chunks)

D:ProgramFilesNoSpaceMiniconda3envspy36libjsonencoder.py in iterencode(self, o, _one_shot)
    255                 self.key_separator, self.item_separator, self.sort_keys,
    256                 self.skipkeys, _one_shot)
--> 257         return _iterencode(o, 0)
    258 
    259 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

D:ProgramFilesNoSpaceMiniconda3envspy36libjsonencoder.py in default(self, o)
    178         """
    179         raise TypeError("Object of type '%s' is not JSON serializable" %
--> 180                         o.__class__.__name__)
    181 
    182     def encode(self, o):

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

这时就需要继承 json.JSONEncoder,重载 default 方法

class MyJsonEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, A):
            return str(o)
        return super().default(self, o)

json.dumps(foo, cls=MyJsonEncoder)

输出:

'{"a": 666, "b": "666"}'
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/664300.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号