Created
December 3, 2018 12:11
-
-
Save aragaer/208e330fb8ac116c0bf948ac862e0bcf to your computer and use it in GitHub Desktop.
json StreamDecoder
This file contains 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
#!/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