jf is a jo alternative, A small utility to safely format and print JSON objects in the commandline.
However, unlike jo, where you build the JSON object by nesting jo outputs,
jf works similar to printf, i.e. it expects the template in YAML format as the first argument, and then the values for the placeholders as subsequent arguments.
As a CLI tool
bash
cargo install jf
Or as a library:
bash
cargo add jf
bash
nix-env -f https://github.com/NixOS/nixpkgs/tarball/nixos-unstable -iA jf
Or download binary from the latest release.
bash
jf TEMPLATE [VALUE]... [NAME=VALUE]...
Where TEMPLATE may contain the following placeholders:
%q, %(NAME)q, %(NAME=DEFAULT)q for quoted and safely escaped JSON string.%s, %(NAME)s, %(NAME=DEFAULT)s for JSON values other than string.And [VALUE]... [NAME=VALUE]... are the values for the placeholders.
%s or %q syntax to declare positional placeholders.%(NAME)s or %(NAME)q syntax to declare named placeholders.%(NAME=DEFAULT)s or %(NAME=DEFAULT)q syntax to declare default values for named placeholders.%% to escape a literal % character.NAME=VALUE syntax.jf version number, run jf %v.Example:
```bash jf "hello: %q" world
jf "hello: {beautiful: %(what)q}" what=world
jf "d: {m: %s, n: %s}" 10 20
jf "{a: {b: %s, c: {d: %s, f: %s}, d: {e: [%s, %q]}}, b: {e: [%q]}}" 0 1 true 2 sam hi
```
rust
let json = match jf::format(["%q", "JSON Formatted"].map(Into::into)) {
Ok(value) => value,
Err(jf::Error::Usage) => {
bail!("usage: mytool: TEMPLATE [VALUE]... [NAME=VALUE]...")
}
Err(jf::Error::Jf(e)) => bail!("mytool: {e}"),
Err(jf::Error::Json(e)) => bail!("mytool: json: {e}"),
Err(jf::Error::Yaml(e)) => bail!("mytool: yaml: {e}"),
};