Programs and the world / JSON, time, URLs and random numbers
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
Kiln04
03 Programs and the world / 02
JSON, time, URLs and random numbers
Data in and out: JSON checked against types, times, URLs, and numbers from a seed.
Much of what comes into a program, and goes out of it, is text in a known format: JSON from another service, a time in a form or a database, a value inside a link. For JSON and times, a built-in class turns the text into a value of a real type and back again, and text that doesn't fit is a failure right there, so the rest of the program only sees values it can trust. For links, URL makes a value safe to put in one, and reads it back out. And when a program needs to make up data of its own, Random gives it numbers from a seed, the same ones every time.
JSON
JSON.decode makes a value of the type given with as: from JSON text, and JSON.encode makes JSON text from a value:
enum Role
member
admin
end
record User
name: String
age: Int
email: String? = nil
role: Role = Role.member
end
const text = "[{\"name\": \"Ada\", \"age\": 36, \"role\": \"admin\"}]"
const users = try JSON.decode(text, as: [User])
print(users[0].role) # prints Role.admin
print(JSON.encode(users[0])) # prints {"name":"Ada","age":36,"email":null,"role":"admin"}as: takes a type: a record, an enum, Int, Float, Boolean, String, or arrays, hashes and T? of those. It's the only place a type is given as an argument.
JSON works with records, not classes. A class's fields can be private, and what leaves a program should be chosen on purpose:
Not this
Give JSON.encode or JSON.decode a class. That's an error before anything runs.
Write this
Copy what should go out into a record, and encode the record.
Fields and keys
Fields match keys by name, and keys the record doesn't have are ignored. When the JSON's name differs, give the field a key, after its type. It counts both ways, in and out:
record Person
first_name: String key "firstName"
end
const person = try JSON.decode("{\"firstName\": \"Ada\"}", as: Person)
print(person.first_name) # prints Ada
print(JSON.encode(person)) # prints {"firstName":"Ada"}- A field with a default, or of a type
T?, may be missing from the JSON;nullfits only aT?. A missing field's default is worked out the waynewdoes it. - Enums go to and from their value's name:
"admin". - Hashes with
Intkeys have them as text in JSON:{"1": "one"}.
When the JSON doesn't fit
JSON.decode can fail, with the kind invalid, and its message says where: [1].age: expected an Int, got "x", or, for text that isn't JSON, line 2, column 9: expected ':' after the key, found '3'.
JSON.encode can't fail. It writes compact JSON, and Floats that JSON can't hold are written as null.
Time
A Time is a moment, the same everywhere, to the millisecond. It shows as ISO 8601 text in UTC, always the same width, so times sort the same as text as they do as times. Text read as a time says its zone, Z or an offset:
const start = try Time.parse("2026-11-24T10:15:00Z")
print(start) # prints 2026-11-24T10:15:00.000Z
print(try Time.parse("2026-11-24 11:15+01:00") == start) # prints true
print(Time.now() > (try Time.parse("2020-01-01T00:00Z"))) # prints true| Use | Gives | |
|---|---|---|
Time.now() | Time | the moment it runs |
Time.parse(text) | Time! | the time the text gives (below) |
String(time) | String | the ISO text, as it prints |
time.plus(days: 3) | Time | later by that much: any of days:, hours:, minutes:, seconds: and milliseconds:, as whole numbers |
time.minus(hours: 2) | Time | earlier by that much, the same way |
later.since(earlier) | Duration | how long from earlier to later |
time.in(zone) | LocalTime | the moment as the zone's clocks show it |
Time.parse reads a date and time (2026-11-24T10:15, with seconds and a fraction if wanted, and a T or a space between) that ends with its zone: Z for UTC, or an offset (+01:00). Anything else fails, with the kind invalid.
Times compare with <, <=, >, >=, == and !=: earlier is less. In JSON and in a database, a time is its ISO text.
A time moves by days, hours, minutes, seconds and milliseconds:
const placed = try Time.parse("2026-11-25T14:02Z")
print(placed.plus(days: 3)) # prints 2026-11-28T14:02:00.000Z
print(placed.minus(hours: 2, minutes: 30)) # prints 2026-11-25T11:32:00.000Z
const waited = placed.plus(days: 2, hours: 5).since(placed)
print(waited) # prints P2DT5H
print(waited.days) # prints 2
print(waited.hours) # prints 53- Months and years aren't among the units: a month after 31 January has no one right answer. A time moved past the years 1 to 9999 is an error.
- A
Durationis how long between two times.days,hours,minutes,secondsandmillisecondssay how long in whole units, rounded toward zero: 53 hours is 2 days. One that goes back (an earlier time'ssincea later one) is negative. Durations compare like times. - A duration prints as ISO 8601:
P2DT5His 2 days and 5 hours,PT1M30Sa minute and a half,PT0Snone at all. - A duration isn't kept as data: it can't go into JSON, a form or a table. Keep the times it's between, or a number, like
waited.seconds.
Zones
What a clock shows, its hour and its date, depends on where it is. A Zone is a place's clocks, named as the IANA time zone database names them; the database is part of hem, the same on every machine. A moment in a zone is a LocalTime, whose parts read like fields:
const copenhagen = Zone.named("Europe/Copenhagen")
const placed = try Time.parse("2026-11-25T14:02Z")
const local = placed.in(copenhagen)
print(local) # prints 2026-11-25T15:02:00.000+01:00
print(local.hour) # prints 15
print(local.weekday) # prints Weekday.wednesday
print(local.date) # prints 2026-11-25
print(placed.in(Zone.utc).hour) # prints 14| Use | Gives | |
|---|---|---|
Zone.named("Europe/Copenhagen") | Zone | the zone of that name; a name written out is checked before the program runs |
Zone.named(name) | Zone! | the same for a name in a variable; one that isn't a zone fails, with the kind invalid |
Zone.utc | Zone | UTC: no offset, ever |
zone.name | String | its name, as it prints |
zone.parse(text) | Time! | text as the zone's clocks show a time: a date (its midnight), or a date and time with no zone of its own |
local.year | Int | and so month (from 1 to 12), day, hour, minute, second and millisecond |
local.weekday | Weekday | Weekday.monday to Weekday.sunday |
local.date | String | its day as ISO text: 2026-11-25 |
local.offset | Duration | how far its clocks are from UTC then: PT1H |
local.time, local.zone | Time, Zone | the moment and the zone it was made from |
const copenhagen = Zone.named("Europe/Copenhagen")
const midnight = try copenhagen.parse("2026-11-24")
const skipped = try copenhagen.parse("2026-03-29T02:30")
print(midnight) # prints 2026-11-23T23:00:00.000Z
print(skipped) # prints 2026-03-29T01:30:00.000Z- A Time has no hour of its own:
time.houris an error that says to ask a zone,time.in(zone).hour. - When the clocks go forward, the times they skip don't happen:
parsemoves such a time on by the gap, so 02:30 on the morning they skip 02:00 to 03:00 is 03:30. When they go back, the times they show twice are the first. - A LocalTime prints with its offset. To show it another way, put its parts together in a string:
"#{local.day}/#{local.month}". - A zone and a local time aren't kept as data. Keep the moment, and the zone's name, and make them again:
Zone.named(name),time.in(zone). - A form's
datetime-localfield sends the time its clock shows,2026-11-24T10:15, with no zone: take it as aString, and read it with the zone it's in,zone.parse(text).
URLs
URL.encode(text) makes text safe inside a URL, like a value in a link's query: letters, digits and -_.~ stay as they are, and everything else becomes % and two hex digits. URL.decode(text) undoes it, and fails (kind invalid) when what it gives isn't UTF-8 text.
print(URL.encode("c++ & more")) # prints c%2B%2B%20%26%20more
print(try URL.decode("caf%C3%A9")) # prints caféIn a template, a value inside a link is encoded first, then escaped as usual: href: "/?tag=#{URL.encode(tag)}".
Random numbers
Random.seeded(seed) makes a generator of numbers from an Int, its seed. The same seed gives the same numbers every time, in every version of Hematite and on every machine, so a program that makes up data, or a test, does the same thing each time it runs:
var dice = Random.seeded(42)
print(dice.int(below: 6)) # prints 0
print(1 + dice.int(below: 6)) # prints 3
print(dice.pick(["S", "M", "L"])) # prints L
print(dice.float()) # prints 0.9246929453253876
var again = Random.seeded(42)
print(again.int(below: 6)) # prints 0| Use | Gives | |
|---|---|---|
Random.seeded(seed) | Random | a generator, from an Int |
random.int(below: n) | Int | changes a number from 0 up to, not with, n, each as likely as the others |
random.float() | Float | changes from 0.0 up to, not with, 1.0 |
random.pick(items) | an item | changes one of the array's items, each as likely |
Each method moves the generator along, so the next number is a new one, and that's why a generator is a var. Numbers from 1 to 6 are 1 + dice.int(below: 6).
A Random is a value, like an array: a copy starts where the original was, and goes its own way. So keep a generator in one place, a variable or an object's field, and move it along there. A class's own method can use self.random.int(below: 6).
intwithbelow:0 or less, andpickwith an empty array, are errors.- The numbers come from xoshiro256**, its state made from the seed by SplitMix64. They're for made-up data, games and tests, not for secrets: anyone who knows the seed knows every number.
- A
Randomisn't data: it can't go into JSON, a form or a table. Keep its seed, and make it again.