Skip to the page
Programs and the world / JSON, time, URLs and random numbers

Start here01

The language02

Programs and the world03

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:

users-json.hem
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:

json-key.hem
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; null fits only a T?. A missing field's default is worked out the way new does it.
  • Enums go to and from their value's name: "admin".
  • Hashes with Int keys 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:

time.hem
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
UseGives
Time.now()Timethe moment it runs
Time.parse(text)Time!the time the text gives (below)
String(time)Stringthe ISO text, as it prints
time.plus(days: 3)Timelater by that much: any of days:, hours:, minutes:, seconds: and milliseconds:, as whole numbers
time.minus(hours: 2)Timeearlier by that much, the same way
later.since(earlier)Durationhow long from earlier to later
time.in(zone)LocalTimethe 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:

time-arithmetic.hem
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 Duration is how long between two times. days, hours, minutes, seconds and milliseconds say how long in whole units, rounded toward zero: 53 hours is 2 days. One that goes back (an earlier time's since a later one) is negative. Durations compare like times.
  • A duration prints as ISO 8601: P2DT5H is 2 days and 5 hours, PT1M30S a minute and a half, PT0S none 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:

zones.hem
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
UseGives
Zone.named("Europe/Copenhagen")Zonethe 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.utcZoneUTC: no offset, ever
zone.nameStringits 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.yearIntand so month (from 1 to 12), day, hour, minute, second and millisecond
local.weekdayWeekdayWeekday.monday to Weekday.sunday
local.dateStringits day as ISO text: 2026-11-25
local.offsetDurationhow far its clocks are from UTC then: PT1H
local.time, local.zoneTime, Zonethe moment and the zone it was made from
zone-parse.hem
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.hour is an error that says to ask a zone, time.in(zone).hour.
  • When the clocks go forward, the times they skip don't happen: parse moves 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-local field sends the time its clock shows, 2026-11-24T10:15, with no zone: take it as a String, 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.

urls.hem
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:

random-numbers.hem
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
UseGives
Random.seeded(seed)Randoma generator, from an Int
random.int(below: n)Intchanges a number from 0 up to, not with, n, each as likely as the others
random.float()Floatchanges from 0.0 up to, not with, 1.0
random.pick(items)an itemchanges 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).

  • int with below: 0 or less, and pick with 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 Random isn't data: it can't go into JSON, a form or a table. Keep its seed, and make it again.