Last active
January 10, 2020 15:11
-
-
Save sloev/f1e3a7cbd922d7babd2662fa04004377 to your computer and use it in GitHub Desktop.
python json stream encoding of generator and array / list using stdlib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # You can use the builtin json lib to iteratively encode a json object | |
| # but encoding a json array iteratively requires the iterable to be list-like | |
| # No worries we just subclass list and pretend to be a list while being able to ingest | |
| # whatever you want | |
| import json | |
| import sys | |
| class IteratorAsList(list): | |
| def __init__(self, it): | |
| self.it = it | |
| def __iter__(self): | |
| return self.it | |
| def __len__(self): | |
| return 1 | |
| generator = ("lolcat" for i in range(10)) | |
| for index, chunk in enumerate( | |
| json.JSONEncoder().iterencode(IteratorAsList(generator)) | |
| ): | |
| sys.stdout.write(chunk) | |
| sys.stdout.flush() | |
| break | |
| # produces: | |
| # ["lolcat" | |
| # which means that the first chunk included the array start bracket | |
| # and the first array member | |
| print() | |
| generator = ("lolcat" for i in range(10)) | |
| for index, chunk in enumerate( | |
| json.JSONEncoder().iterencode(IteratorAsList(generator)) | |
| ): | |
| sys.stdout.write(chunk) | |
| sys.stdout.flush() | |
| # produces | |
| # ["lolcat", "lolcat", "lolcat", "lolcat", "lolcat", "lolcat", "lolcat", "lolcat", "lolcat", "lolcat"] | |
| # one line with start and end brackets |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment