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.

Author altvod
Recipients altvod
Date 2016-07-25.11:42:11
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1469446931.7.0.792781039481.issue27613@psf.upfronthosting.co.za>
In-reply-to
Content
JSONEncoder.iterencode doesn't work with empty iterators correctly.
Steps:
1. Define an iterator that is recognized by json as a list (inherit from list and define nonzero __len__).
2. Use json.dump with data containing an empty iterator defined as described in step#1 (but doesn't generate any items)

Expected result: it should be rendered as an empty list: '[]'

Actual result: it is rendered as ']' (only the closing bracket)
interestingly enough this behavior is not reproduced when using the dumps function.
I tried other alternatives to the standard json module: simplejson, ujson, hjson
All of them work as expected in this case (both brackets are rendered).

Here is an example of the code that demonstrates this error (compares the results of the dump and dumps functions):


import json as json
import io

class EmptyIterator(list):
    def __iter__(self):
        while False:
            yield 1
    def __len__(self):
        return 1

def dump_to_str(data):
    return json.dumps(data)

def dump_to_file(data):
    stream = io.StringIO()
    json.dump(data, stream)
    return stream.getvalue()


data = {'it': EmptyIterator()}
print('to str: {0}'.format(dump_to_str(data)))
print('to file: {0}'.format(dump_to_file(data)))



This prints:
to str: {"it": []}
to file: {"it": ]}
History
Date User Action Args
2016-07-25 11:42:11altvodsetrecipients: + altvod
2016-07-25 11:42:11altvodsetmessageid: <1469446931.7.0.792781039481.issue27613@psf.upfronthosting.co.za>
2016-07-25 11:42:11altvodlinkissue27613 messages
2016-07-25 11:42:11altvodcreate