Skip to content

Instantly share code, notes, and snippets.

@aragaer
Created December 3, 2018 12:11
Show Gist options
  • Save aragaer/208e330fb8ac116c0bf948ac862e0bcf to your computer and use it in GitHub Desktop.
Save aragaer/208e330fb8ac116c0bf948ac862e0bcf to your computer and use it in GitHub Desktop.
json StreamDecoder
#!/usr/bin/env python3
import json
class StreamDecoder(json.JSONDecoder):
def __init__(self, *args, buf=None, **kwargs):
super().__init__(*args, **kwargs)
self.buf = buf or [""]
def decode(self, string):
self.buf[0] = (self.buf[0]+string).lstrip()
doc, offt = self.raw_decode(self.buf[0])
self.buf[0] = self.buf[0][offt:]
return doc
if __name__ == '__main__':
import sys
buf = [""]
while True:
try:
d = json.load(sys.stdin, cls=StreamDecoder, buf=buf)
except json.decoder.JSONDecodeError:
print("End of stream")
break
print(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment