Skip to content

Instantly share code, notes, and snippets.

@sloev
Last active January 10, 2020 15:11
Show Gist options
  • Select an option

  • Save sloev/f1e3a7cbd922d7babd2662fa04004377 to your computer and use it in GitHub Desktop.

Select an option

Save sloev/f1e3a7cbd922d7babd2662fa04004377 to your computer and use it in GitHub Desktop.
python json stream encoding of generator and array / list using stdlib
# 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