This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Allow namedtuple to be JSON encoded as dict
Type: behavior Stage:
Components: Versions: Python 3.6, Python 3.2, Python 3.3, Python 3.4, Python 3.5, Python 2.7
process
Status: closed Resolution: duplicate
Dependencies: Superseder: Cannot override JSON encoding of basic type subclasses
View: 12657
Assigned To: Nosy List: Zack--, eric.smith, ezio.melotti, pitrou, rhettinger, serhiy.storchaka
Priority: normal Keywords:

Created on 2015-02-17 16:52 by Zack--, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (4)
msg236139 - (view) Author: Zack (Zack--) Date: 2015-02-17 16:52
We used to be able to override _iterencode prior to 2.7 to get our namedtuples to be encoded as dict using json.dump(s) but now we can not.

Namedtuples are automatically encoded as list but it would be more logical and convenient to have them encoded as dict
msg236170 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2015-02-18 12:44
Can you post a code snippet that used to work, but now does not?
msg236171 - (view) Author: Zack (Zack--) Date: 2015-02-18 12:53
From memory, something along the lines of 

from json import JSONEncoder

class ExtendedJSONEncoder(JSONEncoder):

    def _iterencode(self, o, markers=None):
        if isinstance(o, tuple) and hasattr(obj, '_fields'):
            gen = self._iterencode_dict(o.__dict__, markers)
        else:
            gen = JSONEncoder._iterencode(self, o, markers)
        for chunk in gen:
            yield chunk
msg236177 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2015-02-18 15:11
This is a duplicate of issue12657.
History
Date User Action Args
2022-04-11 14:58:12adminsetgithub: 67661
2015-02-18 15:11:02serhiy.storchakasetstatus: open -> closed

nosy: + serhiy.storchaka
messages: + msg236177

superseder: Cannot override JSON encoding of basic type subclasses
resolution: duplicate
2015-02-18 12:53:37Zack--setmessages: + msg236171
2015-02-18 12:44:01eric.smithsetnosy: + eric.smith
messages: + msg236170
2015-02-17 16:52:36Zack--create