Skip to content

Convert between config formats

json, yaml and toml all read into the same json.Json tree, so converting a file is reading it with one module and writing it with another. This program reads a YAML file, checks one setting, and writes the same data as TOML and as JSON. ini and xml have trees of their own, since their data does not have the same shape.

import fs
import json
import toml
import yaml
let tmp = try fs.temp_dir()
let source = tmp.join(&"app.yaml")
try fs.write(&source, &"name: shop\nport: 8080\ndatabase:\n host: db.internal\n pool: 10\nfeatures: [search, cart]\n")
let conf = yaml.parse(&(try fs.read(&source))) catch |e| {
print(f"{source}:{e.line}: {e.message}")
return
}
match conf.get(&"port").unwrap_or(&json.Json.Null).int() {
Some(p) => print(f"port {p}")
None => print("port must be a whole number")
}
let as_toml = toml.text(&conf) catch |e| {
print("cannot write TOML: " + e.message)
return
}
try fs.write(&tmp.join(&"app.toml"), &as_toml)
print(as_toml)
print(json.pretty(&conf))
port 8080
name = "shop"
port = 8080
features = ["search", "cart"]
[database]
host = "db.internal"
pool = 10
{
"name": "shop",
"port": 8080,
"database": {
"host": "db.internal",
"pool": 10
},
"features": [
"search",
"cart"
]
}

Things that do not carry over:

  • TOML has no null, so toml.text refuses a document holding one and says where it is.
  • TOML dates are read as text, so they come out as quoted strings.
  • Comments are not part of the tree and are lost in every conversion.