Numbers and JSON#
Parse integers and JSON, and read and write typed JSON. Each program is a complete .ms file: save it under the shown name and run the command from that directory (getting started
). main returns the exit status.
Parse an integer#
Save as number.ms. parse_int() returns an Int?.
Manuscript
import (
stdout from "@std/io/io.ms",
arguments from "@std/os/env.ms",
)
fn show(number Int) Result[Void, Error] {
stdout().write(f"{number}\n")?
return stdout().flush()
}
fn main() Int {
number := arguments().get_or(0, "42").parse_int()
if number != null and show(number).is_ok() { return 0 }
return 1
}sh
ms run number.ms -- 42text
42Use x or default for a default, or compare with null and take a failure path (Optional values
).
Parse JSON#
Save as json.ms. parse[String] errors on malformed JSON or another type.
Manuscript
import (
parse from "@std/data/json.ms",
stdout from "@std/io/io.ms",
arguments from "@std/os/env.ms",
)
fn run() Result[Void, Error] {
text := parse[String](arguments().get_or(0, "\"hello\""))?
stdout().write(f"{text}\n")?
return stdout().flush()
}
fn main() Void! {
return run()
}sh
ms run json.ms -- '"hello"'text
helloWithout a type, parse returns a JsonValue tree for unknown shapes.
Read and write typed JSON#
Save as config.ms. Parse into a type directly and serialize it back. Use strict encoding so a value with no JSON representation fails instead of being silently omitted.
Manuscript
import (
StringifyOptions, parse, stringify from "@std/data/json.ms",
stdout from "@std/io/io.ms",
arguments from "@std/os/env.ms",
)
type Config {
name String
enabled Bool = true
}
fn run() Result[Void, Error] {
text := arguments().get_or(0, "{\"name\":\"Sam\"}")
config := parse[Config](text)?
encoded := stringify(config, StringifyOptions(strict: true))?
stdout().write(f"{encoded}\n")?
return stdout().flush()
}
fn main() Void! {
return run()
}sh
ms run config.ms -- '{"name":"Sam"}'text
{"name":"Sam","enabled":true}- A missing
enabledtakes its default; a missingnameor wrong type is an error. - Unknown members are ignored unless
JsonOptions(ignore_unknown_fields: false). - Write the type argument explicitly:
parse[Config](text)?. stringifywrites fields in declaration order.StringifyOptions(strict: true)is opt-in; ordinarystringifycan omit values without a JSON form. Strict mode still omitsnullfields.