1

Trying to compress some data in Python (think API backend) then open and decompress in JS (frontend).

Python

zlib.compress(bytes(json.dumps(["a", "b", "c"]), "utf-8"))

This produces a byte object

b'x\x9c\x8bVJT\xd2QPJ\x02\x11\xc9J\xb1\x00\x1a\x13\x03C'

How do I parse this and decompress this with JavaScript?

mlevit
  • 2,676
  • 10
  • 42
  • 50
  • I don't think JS can interpret Python's representation of `bytes`. base64 encode the `bytes` that `zlib.compress` returns - `base64.b64encode(zlib.compress(bytes(json.dumps(["a", "b", "c"]), "utf-8"))).decode('ascii')`. – GordonAitchJay Jul 12 '22 at 05:04
  • @python_user I'm trying to use pako but I don't know how to convert the Python byte object to Uint8Array which pako is expecting. – mlevit Jul 12 '22 at 05:05

1 Answers1

2

Thanks to @GordonAitchJay for the tip there. Got there in the end.

On the Python side we have

json_object = ["a", "b", "c"]
base64.b64encode(zlib.compress(bytes(json.dumps(json_object), "utf-8"))).decode("ascii")

On the JS side we have

let compressedData = Uint8Array.from(atob(input), (c) => c.charCodeAt(0));
let decompressedData = pako.inflate(compressedData, { to: "string" });
let jsonObject = JSON.parse(decompressedData);
mlevit
  • 2,676
  • 10
  • 42
  • 50
  • Very helpful! Was missing the base64 encoding and the whole conversion stuff on JS side. Works like a charm now! You would imagine this would be easier.. – Akaisteph7 Jan 17 '23 at 23:08