Simply encode and decode discriminated unions into a binary format.
npm install json-or-binaryAll values must follow the {type: string, value: unknown} structure.
import { encode, decode } from 'json-or-binary';
// JSON mode (for non-binary values)
const encoded = encode({ type: 'message', value: 'hello' });
// Result: {"type":"message","value":"hello"}
const decoded = decode(encoded);
// Result: { type: 'message', value: 'hello' }
// Binary mode (for Uint8Array values)
const binaryEncoded = encode({
type: 'image',
value: new Uint8Array([1, 2, 3])
});
// Result: "image"<binary data>
const binaryDecoded = decode(binaryEncoded);
// Result: { type: 'image', value: Uint8Array([1, 2, 3]) }- Input: Always
{type: string, value: any} - JSON mode: Uses standard JSON when
valueis notUint8Array - Binary mode: Uses
"type"<binary>format whenvalueisUint8Array - Auto-detection: Decoder detects format by first byte (
{or") - Constraint: Type field cannot contain
"character
Encodes a discriminated value to binary format.
Decodes binary data back to discriminated value. Consider validating output with zod, Typebox, or similar for type safety.
MIT