Skip to content

Instantly share code, notes, and snippets.

@charlieanstey
Last active October 16, 2022 22:23
Show Gist options
  • Save charlieanstey/8ec4b4cd5d7cbec1624a9491d39ebdfe to your computer and use it in GitHub Desktop.
Save charlieanstey/8ec4b4cd5d7cbec1624a9491d39ebdfe to your computer and use it in GitHub Desktop.
URL-safe encoding/decoding of JSON data like Pendo does it
// 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