Last active
October 16, 2022 22:23
-
-
Save charlieanstey/8ec4b4cd5d7cbec1624a9491d39ebdfe to your computer and use it in GitHub Desktop.
URL-safe encoding/decoding of JSON data like Pendo does it
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
// Given large data payload with UTF-6 encoding, emojis etc. | |
const data = [{...}] | |
const string = JSON.stringify(data); // JSON to string | |
const byteArray = new TextEncoder().encode(string) // Convert to bytes | |
const deflatedByteArrayBuffer = zlib.deflateSync(byteArray); // Compress | |
const encoded = deflatedByteArrayBuffer.toString("base64url"); // Encode for safe transfer e.g. via URL | |
// URL-safe output | |
console.log(encoded) | |
// ----- | |
const decoded = Buffer.from(encoded, "base64url") | |
const inflatedBuffer = zlib.inflateSync(decoded); // Decompress | |
const dataString = new TextDecoder().decode(inflatedBuffer) // Bytes to string | |
const originalData = JSON.parse(dataString); // string to JSON | |
// Original data | |
console.log(originalData) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment