bpo-31155: Encode set, frozenset, bytearray, and iterators as json arrays by onealj · Pull Request #3034 · python/cpython

@onealj

Based on a discussion on Stack Overflow
https://stackoverflow.com/questions/45457946/python-efficient-reverse-list-json-serialisation/45458128#45458128

I wrote out a solution that is general enough to support most of core Python.

If there are performance issues with the `iterable_types` nonlocal lookup, these could be pulled in as local variables to the inner `_iterencode_*` functions.

As written, a user would have to monkey patch `json.encoder._get_iterable_types()` (or one of the functions it calls) if they wanted to be able to encode their own sequence-like containers or iterators as a json array.

If there are plans for the json library to sequence-like classes and iterators that are part of the core language, part of the standard library, and in third party modules, then some modifications will be needed so that monkey patching isn't necessary.

These changes are contributed under the Python Software License 2.0 or similar. I can sign a contributor license agreement if needed.

onealj

@onealj onealj changed the title Encode set, frozenset, bytearray, and iterators as json arrays bpo-31155: Encode set, frozenset, bytearray, and iterators as json arrays

Aug 9, 2017

@onealj

If the user passes in an iterator to a dict rather than the dict itself, handle the special dict_keys, dict_values, or dict_items iterators for serialization as a json array (perhaps the dict_itemiterator should write out a json dictionary instead).