Parse an INI Config File in Larzscript
Read a classic `[section]` / `key = value` config file into a nested dict.
No dedicated package for INI in the stack yet - a short hand-written parser (skip comments and blank lines, track the current section header, split each `key = value` line once) covers the common real-world subset.
Code
fn parse_ini(text) {
let sections = {"": {}}
let current = ""
for raw_line in text.split("\n") {
let line = raw_line.strip()
if len(line) == 0 or line.starts_with(";") or line.starts_with("#") { continue }
if line.starts_with("[") and line.ends_with("]") {
current = line[1:len(line)-1]
sections[current] = {}
continue
}
let eq = line.find("=")
if eq < 0 { continue }
let key = line[0:eq].strip()
let value = line[eq+1:].strip()
sections[current][key] = value
}
return sections
}
let ini_text = "[server]\nhost = 0.0.0.0\nport = 8080\n\n[database]\nname = larzbank\ntimeout = 30\n"
let cfg = parse_ini(ini_text)
print(cfg["server"]["host"], cfg["server"]["port"])
print(cfg["database"]["name"], cfg["database"]["timeout"])Output
0.0.0.0 8080 larzbank 30
Related
Parse JSON in LarzscriptParse a JSON string into real Larzscript dicts and lists, and turn data back into JSON text.→Read and Parse a CSV File in LarzscriptParse CSV text into rows, or straight into dicts keyed by header - including quoted fields with embedded commas.→Encode and Decode Base64 in LarzscriptBase64-encode arbitrary text (or decode it back), the standard way binary-ish data travels safely through text-only channels like JSON or URLs.→Parse a URL in LarzscriptBreak a URL into its scheme, host, path and query parameters, and safely join a base URL with a relative path.→