Reading YAML by path, building and writing it, and converting it to JSON.
import encoding.yaml
YAML is the usual format for configuration files. This package converts YAML to JSON internally, which is what makes its reading functions simple and what lets it work alongside the json package.
The reading functions take a path: keys separated by dots, with a list index in square brackets, as in app.hosts[1]. A path that is not there gives an empty string or zero; to tell that apart from a real value, use Has.
It reads the YAML that configuration files use: nested maps, lists in dashed and [flow] form, quoted strings, | and > block text, comments and several documents. For flat key = value settings with sections and overrides, config is simpler, and it reads YAML too.
The things people get wrong:
•
Anchors and aliases (&base, *base, <<: *base) are not supported. A value like &a 1 is read as the string &a 1, and an anchor on a map, as in base: &base followed by indented keys, loses the rest of the document without an error. Write such files out in full, or expand them with another tool first.
•
yes, no, on and off are strings, as in YAML 1.2, so GetBool is false for them. Only true and false are booleans.
•
GetInt returns a 32-bit int and gives 0 for larger numbers. Read sizes, ids and timestamps through ToJSON into an i64 field (see below).
•
Every path function parses the whole text again. For many reads from a large file, call ToJSON or Decode once and work on the result.
Guide: read a config file with defaults
The path functions are the quickest way to read a config file. Check first that the sections you depend on exist with HasKeys, then read each setting with the typed getter. For optional settings, wrap Get in a small helper that falls back to a default when Has says the key is not there.
listen on 0.0.0.0:8080
workers: 4
log level: debug
log file: stdout
search on: true beta on: false
feature flags: ["search", "beta"]
Comments starting with # are ignored. GetInt and GetBool return 0 and false for a missing key, which is also a real value, so a default other than zero needs the Has check.
Guide: YAML into a struct
For a config with many fields, a struct is easier to pass around than a text and a list of paths. There is no YAML Unmarshal of its own, but there does not need to be: ToJSON turns the YAML into JSON, and encoding.json fills the struct, with the same @json names and defaults.
encoding-yaml-guide-struct.salam
import encoding.yaml
import encoding.json
structService:
pub name: str = ""pub image: str = ""pub replicas: int = 1pub ports: Vector<int> = Vector {}
endfuncmain:
text := `name: api
image: shop/api:2.3
ports:
- 80
- 443
`mut s := Service {}
try:
json.UnmarshalLenient(yaml.ToJSON(text), s)
catch e:
println"bad service:", e.ToStr()
ret1endprintln s.name, "runs", s.image
println"replicas:", s.replicas
println"ports:", s.ports.Len(), s.ports.Get(0), s.ports.Get(1)
end
Output
api runs shop/api:2.3
replicas: 1
ports: 2 80 443
replicas is not in the file, so it keeps its default of 1 because the lenient form was used. With json.Unmarshal the missing key would be an error.
Guide: walk a list of records
A list of objects, such as the jobs of a CI file, is read with Len and an index in the path. Build the path for item i once and add the field names to it. [lint] is the short flow form of a list, and reads the same way as the dashed form.
encoding-yaml-guide-list.salam
import encoding.yaml
importstrfuncmain:
text := `jobs:
- name: lint
run: salam format --check
- name: test
run: sh tests/run.sh
needs: [lint]
- name: deploy
run: sh deploy.sh
needs: [test]
branch: main
`
n := yaml.Len(text, "jobs")
println n, "jobs"repeat n in i:
at := "jobs[" + str.FromInt(i) + "]"
line := yaml.Get(text, at + ".name") + ": " + yaml.Get(text, at + ".run")
if yaml.Has(text, at + ".needs"):
println line, "(after", yaml.Get(text, at + ".needs[0]") + ")"else:
println line
endif yaml.Has(text, at + ".branch"):
println" only on", yaml.Get(text, at + ".branch")
endendend
Output
3 jobs
lint: salam format --check
test: sh tests/run.sh (after lint)
deploy: sh deploy.sh (after test)
only on main
Guide: several documents in one file
Kubernetes manifests and some log formats put several YAML documents in one file, separated by a line with ---. SplitDocuments cuts them apart, and each piece is then an ordinary YAML text for the other functions.
encoding-yaml-guide-multi.salam
import encoding.yaml
funcmain:
text := `kind: Deployment
metadata:
name: web
spec:
replicas: 3
---
kind: Service
metadata:
name: web
spec:
port: 80
---
kind: ConfigMap
metadata:
name: web-config
`
docs := yaml.SplitDocuments(text)
println docs.Len(), "documents"each d in docs:
println"-", yaml.Get(d, "kind"), yaml.Get(d, "metadata.name"), "valid:", yaml.Valid(d)
endprintln"deployment as JSON:", yaml.ToJSON(docs.Get(0))
end
Output
3 documents
- Deployment web valid: true
- Service web valid: true
- ConfigMap web-config valid: true
deployment as JSON: {"kind": "Deployment", "metadata": {"name": "web"}, "spec": {"replicas": 3}}
ToJSON is also how you hand YAML to anything that speaks JSON, such as an HTTP API. Going the other way, Dump writes JSON text as YAML.
Guide: what type did the value get?
YAML decides the type of a value from how it looks, and the result is not always what the author meant. TypeOf shows what the reader saw. Here yes stayed a string, 007 kept its zeros as a string, and the five gigabyte limit is too big for GetInt but fine for an i64 field.
public is a string so GetBool says false
code is a string with the text 007
GetInt cannot hold it: 0
as JSON: {"max_upload": 5368709120, "public": "yes", "code": "007"}
refused: value does not match the expected type
loaded: 5368709120 true 007
The struct route also checks the types for you: public: yes is refused instead of read as false. Writing true and quoting values that must stay text, such as "007", makes the file mean the same to every reader.