1 Basic usage
With this package installed, you can add #lang toml/config to the top of any TOML file to make it a Racket module that parses its contents into a hash table.
Open DrRacket and create a new file with these contents:
"example.toml.rkt"
#lang toml/config # This is a TOML document title = "TOML Example" [database] enabled = true ports = [ 8000, 8001, 8002 ] data = [ ["delta", "phi"], [3.14] ] temp_targets = { cpu = 79.5, case = 72.0 }
A #lang toml/config module parses its contents to a hash table and binds it to a toml identifier. To see this, press the ▶️ Run button in DrRacket and then evaluate toml as an expression in the REPL:
> toml
'#hasheq((database
.
#hasheq((data . (("delta" "phi") (3.14)))
(enabled . #t)
(ports . (8000 8001 8002))
(temp_targets . #hasheq((case . 72.0) (cpu . 79.5)))))
(title . "TOML Example"))
Since toml is a normal hash table, you can access its values using the normal functions:
> (hash-ref toml 'title) "TOML Example"
You can also use toml-ref for easy access to values inside nested hash tables:
> (toml-ref toml 'database.temp_targets.cpu) 79.5
1.1 Importing data from TOML modules
A #lang toml/config module provides its toml binding. With the above TOML file saved as "example.toml.rkt" you can create the following file in the same folder:
"prog.rkt"
#lang racket/base (require toml/config "example.toml.rkt")
Running this file in DrRacket, you can use the imported toml binding:
> (toml-ref toml 'database.ports) '(8000 8001 8002)
1.2 Custom TOML #langs
The functionality shown so far isn’t much more useful than simply running parse-toml on a normal ".toml" file, except that the files are nicer to edit in DrRacket.
What’s more interesting is using this library for quick customized #langs that validate their contents.
As an example, below is the source for "config/demo.rkt", which this package installs along with its docs:
"demo.rkt"
#lang racket/base (module reader toml/config/custom #:schema ([title string? required] [port (integer-in 1 65535) (optional 8080)]))
Now a TOML module can use this custom #lang:
#lang toml/config/demo title = "My data"
Examining the file’s toml binding:
> toml '#hasheq((port . 8080) (title . "My data"))
Note that the resulting hash table has a key for 'port even though it wasn’t present in the TOML source. This is because the schema in "demo.rkt" specified port as optional and gave it a default value.
Changing the file so that the required title key is no longer present:
BLOOP = "My data"
Results in a compile-time error:
title: required key is missing
→ Add 'title = <value>' to the configuration