Encoding and Decoding
Risor provides two built-in functions, encode and decode, for serializing
and deserializing data in common formats.
Supported Formats
| Format | Description |
|---|---|
json | JSON encoding and decoding |
base64 | Base64 encoding and decoding |
base32 | Base32 encoding and decoding |
hex | Hexadecimal encoding and decoding |
csv | CSV encoding and decoding |
urlquery | URL query string encoding and decoding |
encode
Encode a value into the specified format. Returns a string or byte sequence depending on the format.
JSON
encode({name: "risor", version: 2}, "json")
// '{"name":"risor","version":2}'
encode([1, 2, 3], "json")
// '[1,2,3]'Base64
encode("hello world", "base64")
// "aGVsbG8gd29ybGQ="
encode(bytes("binary data"), "base64")
// "YmluYXJ5IGRhdGE="Base32
encode("hello", "base32")
// "NBSWY3DP"Hex
encode("hello", "hex")
// "68656c6c6f"
encode(bytes([255, 0, 128]), "hex")
// "ff0080"CSV
encode([["name", "age"], ["Alice", "30"]], "csv")
// "name,age\nAlice,30\n"URL Query
encode("hello world", "urlquery")
// "hello+world"
encode("a=1&b=2", "urlquery")
// "a%3D1%26b%3D2"decode
Decode data from the specified format back into a Risor value.
JSON
decode('{"name": "risor"}', "json")
// {name: "risor"}
decode("[1, 2, 3]", "json")
// [1, 2, 3]Base64
decode("aGVsbG8gd29ybGQ=", "base64")
// bytes("hello world")Base32
decode("NBSWY3DP", "base32")
// bytes("hello")Hex
decode("68656c6c6f", "hex")
// bytes("hello")CSV
decode("name,age\nAlice,30\n", "csv")
// [["name", "age"], ["Alice", "30"]]URL Query
decode("hello+world", "urlquery")
// "hello world"
decode("a%3D1%26b%3D2", "urlquery")
// "a=1&b=2"Round-Trip Example
Encoding and decoding are complementary operations. A round-trip preserves the original value:
let data = {users: ["alice", "bob"], count: 2}
let encoded = encode(data, "json")
let decoded = decode(encoded, "json")
// decoded == data