Data formats
Five namespaces turn values into text and back. Json and Csv read and write structured data. Encoding writes Bytes as hex or base64 text and reads them back. Crypto hashes and signs Bytes. Html is the markup that HTML expressions build and String.from renders.
Json.stringify(Map{ "ok": true }) // "{\"ok\":true}"
Csv.stringify([["a", "b, c"]]) // "a,\"b, c\"\n"
Csv.parse("a\tb\n1\t2", sep: "\t") // Ok{ value: [["a", "b"], ["1", "2"]] }
"hi".toBytes() | Encoding.toBase64() // "aGk="
"hi".toBytes() | Crypto.sha256() | Encoding.toHex() // "8f434346648f6b96df89dda901c5176b10a6d83961dd3c1ac88b59b2dc327aa4"
String.from(<b>{"Tom & Jerry"}</b>) // "<b>Tom & Jerry</b>"Each one works on values in memory. Read the text with File.read or Http first, and write the result the same way.
- Json.parse gives a Json.Value to narrow with
is, with every number afloat64. Json.stringify writes any value that has a JSON form, records included. - Every CSV field is a
string, both ways. Convert numbers yourself. - Encoding and Crypto take
Bytes. Turn text into bytes with String.toBytes, and back with String.fromBytes. Htmlcomes from HTML expressions, never from parsing a string. Text in it is escaped when it renders.- The parsers and decoders return a
Result: malformed input is anErr, not a panic.
Functions by job
JSON
- Json.parse: one JSON text as a
Json.Value, or anErrthat says where it went wrong - Json.stringify: the JSON text of any value, compact or indented with
indent: - Json.Value: a JSON value of unknown shape, narrowed with
is
CSV
- Csv.parse: the rows of CSV text, each an array of string fields; another separator with
sep:, such as"\t" - Csv.stringify: CSV text for rows, quoting the fields that need it; another separator with
sep:
Bytes as text
- Encoding.toHex: bytes as two lower-case hex digits each
- Encoding.fromHex: hex digits of either case back into bytes
- Encoding.toBase64: bytes as base64, standard or URL-safe with
url: - Encoding.fromBase64: base64 back into bytes, with or without padding; URL-safe with
url: - String.toBytes: the UTF-8 bytes of a string
- String.fromBytes: the string that UTF-8 bytes spell, or
null
Hashing
- Crypto.sha256: the 32-byte SHA-256 digest
- Crypto.sha512: the 64-byte SHA-512 digest
- Crypto.sha1: the 20-byte SHA-1 digest, for formats that still use it
- Crypto.md5: the 16-byte MD5 digest, for formats that still use it
Signing messages
- Crypto.hmacSha256: the HMAC-SHA-256 of a message under a key
- Crypto.hmacSha512: the HMAC-SHA-512
- Crypto.hmacSha1: the HMAC-SHA-1
- Crypto.equal: whether two byte sequences match, in time that does not depend on their contents
Tokens and ids
- Crypto.randomBytes:
nbytes from the operating system's secure source - Crypto.uuid: a random version 4 UUID
Markup
- HTML expressions: the syntax that builds
Html, such as<p>{name}</p> - Html.unsafe: a string of trusted markup as
Html, rendered unescaped - Html.nodes: the top-level nodes of an
Html, in order - Html.Node: one node, an element, a text node, or raw markup
- Html.Attribute: one attribute of an element
- Html.Attributes: the map an attribute spread
{...attrs}takes - String.from: the markup of an
Htmlas a string
Applications
Read a field from JSON
Parse the text, then narrow the Json.Value with is before using it. is takes Map without type arguments:
let doc = try Json.parse("{\"name\": \"Ann\"}")
if doc is Map && doc["name"] is string {
println(doc["name"])
}AnnConvert CSV to JSON
Parse the rows, turn each one after the header into a record, and write the records as JSON. Result.all gives the error of the first bad row:
type Person = { name: string, age: int }
func toPerson(row: Array[string]): Result[Person, Error] {
let age = row.get(1)?.toInt() ?? return Result.fail("bad row ${row}")
Result.ok(Person{ name: row[0], age })
}
let rows = try Csv.parse("name,age\nAnn,31\nBob,27")
let people = try (rows.slice(1, rows.length()).map(toPerson) | Result.all())
println(Json.stringify(people, indent: " "))[
{
"name": "Ann",
"age": 31
},
{
"name": "Bob",
"age": 27
}
]Sign a JSON payload
Send the body with the hex HMAC of its bytes, and check a received signature with Crypto.equal:
type Event = { action: string, id: int }
func sign(secret: string, body: string): string {
Crypto.hmacSha256(secret.toBytes(), body.toBytes()) | Encoding.toHex()
}
func verify(secret: string, body: string, signature: string): bool {
let received = Encoding.fromHex(signature)
if received is Err { return false }
Crypto.equal(received.value, Crypto.hmacSha256(secret.toBytes(), body.toBytes()))
}
let body = Json.stringify(Event{ action: "opened", id: 7 })
let signature = sign("hook-secret", body)
println(body)
println(verify("hook-secret", body, signature))
println(verify("hook-secret", body.replace("7", "8"), signature)){"action":"opened","id":7}
true
falseCarry a file in JSON
JSON has no form for Bytes. Write the bytes as base64 next to their digest, and check the digest after decoding:
type Blob = { sha256: string, data: string }
func pack(data: Bytes): Blob {
Blob{ sha256: data | Crypto.sha256() | Encoding.toHex(), data: data | Encoding.toBase64() }
}
func unpack(blob: Blob): Result[Bytes, Error] {
let data = try (Encoding.fromBase64(blob.data) | Result.wrapErr("data"))
if (data | Crypto.sha256() | Encoding.toHex()) != blob.sha256 {
return Result.fail("sha256 does not match")
}
Result.ok(data)
}
let blob = pack(Bytes.fromArray([0x89, 0x50, 0x4e, 0x47]))
println(Json.stringify(blob))
println(unpack(blob))
println(unpack(Blob{ sha256: blob.sha256, data: "AAAA" })){"sha256":"0f4636c78f65d3639ece5a064b5ae753e3408614a14fb18ab4d7540d2c248543","data":"iVBORw=="}
Ok{ value: Bytes(89 50 4e 47) }
Err{ error: Error{ message: "sha256 does not match" } }Render CSV as an HTML table
Build the table with HTML expressions. A field that holds markup renders as text:
func table(rows: Array[Array[string]]): Html {
let head = rows[0].map({ <th>{x}</th> })
let body = rows.slice(1, rows.length()).map({ <tr>{x.map({ <td>{x}</td> })}</tr> })
<table><tr>{head}</tr>{body}</table>
}
let rows = try Csv.parse("item,note\ntea,\"<b>hot</b>\"")
println(table(rows))<table><tr><th>item</th><th>note</th></tr><tr><td>tea</td><td><b>hot</b></td></tr></table>Give a page a version tag
A rendered page is a string, so its digest names its content, as an HTTP ETag does:
let page = <html><body><h1>Ants</h1></body></html>
let tag = String.from(page).toBytes() | Crypto.sha256() | Encoding.toHex()
tag.slice(0, 12) // "9fba62fe440b"Make a token and an id
let token = Crypto.randomBytes(24) | Encoding.toBase64(url: true)
token.length() // 32
Crypto.uuid().length() // 36Possible issues
JSON numbers come back as floats
Json.parse(Json.stringify(Map{ "n": 1 })) // Ok{ value: Map{ "n": 1.0 } }Convert with Math.toInt where you need an int.
Bytes and Html have no JSON form
Json.stringify panics on them. Write the base64 of the bytes and the rendered markup instead:
Json.stringify("hi".toBytes()) // panic: Json.stringify: Bytes has no JSON form; write Encoding.toBase64 of it
Json.stringify(<p>hi</p>) // panic: Json.stringify: Html has no JSON form; write String.from of itCSV fields stay strings
Numbers in a CSV file compare as text until you convert them:
let row = Csv.parse("9,10").unwrap()[0]
row[0] < row[1] // false
row.map({ x.toInt() }) // [9, 10]A string is not Bytes, and not markup
Convert text with String.toBytes before hashing or encoding it. A string never becomes Html; interpolate it as text, or pass trusted markup through Html.unsafe:
let digest = Crypto.sha256("abc") // error: cannot use string where Bytes is expected
let h: Html = "<b>x</b>" // error: cannot use string where Html is expectedBase64 has two alphabets
fromBase64 reads only the alphabet url: names, so a URL-safe token needs url: true:
Encoding.fromBase64("-_8") // Err{ error: Error{ message: "illegal base64 data at input byte 0" } }
Encoding.fromBase64("-_8", url: true) // Ok{ value: Bytes(fb ff) }Encoding is not encryption
Anyone can decode hex and base64, and anyone can compute a digest of public data. Sign with an HMAC under a secret key, and make secrets with Crypto.randomBytes, not with a seeded Random generator.
See also
- HTML expressions guide: how markup, components, and rendering fit together
- Working with text: strings, bytes, and regular expressions
- Files and paths: reading and writing the files that hold these formats
- Network: sending and receiving them over HTTP
- How-to: hash data and compare hashes
