Created
January 22, 2019 12:27
-
-
Save busybus/fd8a5fccb57ae09f67b090515ce1e37f to your computer and use it in GitHub Desktop.
Compress/decompress JSON (2)
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
import zlib, json, base64 | |
ZIPJSON_KEY = 'base64(zip(o))' | |
def json_unzip(j, insist=True): | |
try: | |
assert (j[ZIPJSON_KEY]) | |
assert (set(j.keys()) == {ZIPJSON_KEY}) | |
except: | |
if insist: | |
raise RuntimeError("JSON not in the expected format {" + str(ZIPJSON_KEY) + ": zipstring}") | |
else: | |
return j | |
try: | |
j = zlib.decompress(base64.b64decode(j[ZIPJSON_KEY])) | |
except: | |
raise RuntimeError("Could not decode/unzip the contents") | |
try: | |
j = json.loads(j) | |
except: | |
raise RuntimeError("Could interpret the unzipped contents") | |
return j |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment