python工具-base64-zip-json

python工具-base64-zip-json

# 先 base64 解码,再 zip 解码,再打印 json 内容,支持多个字符串解码

import sys
import base64
import zlib
import json

def enc_json_zip_base64(input_data):
    json_object = json.loads(input_data)
    zip_data = zlib.compress(json.dumps(json_object).encode("utf-8"))
    base64_data = base64.b64encode(zip_data)
    return base64_data

def dec_base64_zip_json(input_data):
    zip_data = base64.b64decode(input_data)
    json_data = zlib.decompress(zip_data)
    json_object = json.loads(json_data)
    return json.dumps(json_object, sort_keys=True, indent=4, separators=(', ', ': '))

# python decode-base64-zip-json.py eJyrVkpJLU5WslKoVjIEkkpJicWpZiYKKanJSjoKSkYgoarMAhjfGMQvKMrMK1HIKs7PAwmZgISKSwsK8otKFHIT8yoVwPJKtbUAd+Mamg==
# input:
# eJyrVkpJLU5WslKoVjIEkkpJicWpZiYKKanJSjoKSkYgoarMAhjfGMQvKMrMK1HIKs7PAwmZgISKSwsK8otKFHIT8yoVwPJKtbUAd+Mamg==

# output:
# {
#     "desc": {
#         "1": "base64 dec", 
#         "2": "zip dec", 
#         "3": "print json", 
#         "4": "support many print"
#     }
# }
if __name__ == "__main__":
    if len(sys.argv) == 1:
        print("need para. \nfor example: python3 base64-zip.py argv1 ...\n")
        data = enc_json_zip_base64('''{
                                "desc":{
                                    "1":"base64 dec",
                                    "2":"zip dec",
                                    "3":"print json",
                                    "4":"support many print"
                                }
                            }''')
        output = dec_base64_zip_json(data)
        print(f"input: {data}\n")
        print(f"output: {output}\n")
        exit()

    for i in range(len(sys.argv)-1):
        # base64_zip_data = '''eJyrVkpJLU5WslKoVjIEkkpJicWpZiYKKanJSjoKSkYgoarMAhjfGMQvKMrMK1HIKs7PAwmZgISKSwsK8otKFHIT8yoVwPJKtbUAd+Mamg=='''
        output = dec_base64_zip_json(sys.argv[i+1])
        print(f"input:\n{sys.argv[i+1]}\n")
        print(f"output:\n{output}\n")

你可能感兴趣的:(工具类,python)