embed compressed json document in python

To embed a compressed JSON document in Python, you can first compress the JSON string using gzip compression, then encode the compressed bytes using base64 encoding, and finally store the encoded string in your Python script as a variable.

Here's an example of how to do this:

main.py
import json
import gzip
import base64

# define your JSON object
my_data = {"name": "John", "age": 30, "city": "New York"}

# convert JSON to a string
my_json_string = json.dumps(my_data)

# compress the string using gzip
compressed_json = gzip.compress(bytes(my_json_string, 'utf-8'))

# encode the compressed bytes using base64
encoded_json = base64.b64encode(compressed_json).decode('utf-8')

# store the encoded string in a Python variable
embedded_json = f"data:application/json;base64,{encoded_json}"

# you can now embed the compressed JSON in your Python code
my_script = f"""
<script>
var my_data = JSON.parse(atob('{encoded_json}'));
console.log(my_data);
</script>
"""
680 chars
27 lines

In this example, my_data is a dictionary that we convert to a JSON string using json.dumps(). We then compress the JSON string using gzip.compress(), and encode the result using base64.b64encode(). Finally, we store the encoded string in the embedded_json variable prefixing it with the data:application/json;base64 data URI scheme.

You can then use the embedded_json variable in your Python script to embed the compressed JSON data in your code. In the example above we create a script tag with a console.log to see the output.

gistlibby LogSnag