Zellio.io

Base64-encode a JSON payload

2 min readLast updated 3 steps · runs on this page

Some places only take a single line with no quotes in it: an HTTP header, an environment variable, a Kubernetes secret. The usual answer is to Base64 a minified JSON document. This recipe does that in order, so the encoded string is as short as it can be and is known to decode into valid JSON.

The steps

  1. 1

    Validate JSONvia Code Formatter

    Encoding invalid JSON produces a string that decodes to garbage on the other side; better to fail here.

  2. 2

    Minify JSONvia Code Formatter

    Whitespace out, so the encoded form is roughly a third shorter than encoding the pretty version.

  3. 3

    Base64 encodevia Base64 Encode / Decode

    Standard Base64 with padding, which is what headers and secrets expect.

Ctrl+Enter runs · nothing leaves this tab

Why minify before encoding

Base64 expands its input by a third, and indentation is input. A pretty-printed document with four-space indents can be twice the size of its minified form, and every byte of that ends up in the header or the secret. Minifying does not change the data, only its layout, and the decoding side sees identical JSON either way.

Standard or URL-safe

This recipe produces standard Base64, whose alphabet includes plus and slash and which pads with equals signs. Headers, environment variables and Kubernetes secrets take that form. A value going into a URL query string or a JWT needs the URL-safe variant, where plus becomes minus and slash becomes underscore and the padding is dropped; the Base64 tool linked from the last step has a switch for it.

# Decoding on the other side, for comparison
echo "$ENCODED" | base64 --decode | jq .

What Base64 is not

It is not encryption. Anyone who sees the encoded string can read the JSON in it by reversing the step, which is why a secret in a Kubernetes manifest is only as protected as the manifest. If the payload must not be readable in transit or at rest, encrypt it first; the text encryptor uses AES-GCM with a password and produces a Base64 blob that can go in the same places.

Questions

Should I strip the padding?
Only if the consumer requires it. Most decoders accept padded input; some reject unpadded. Keep it unless the documentation for the destination says otherwise.
Is there a size limit for headers?
Servers commonly cap a single header around 8 KB. If the encoded JSON is larger than that, send it in the body instead.