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
bash
jf TEMPLATE [VALUE]... [NAME=VALUE]...
Where TEMPLATE may contain the following placeholders:
%q for quoted and safely escaped JSON string.%s for JSON values other than string.%v for the jf version number.%% for a literal % character.And [VALUE]... [NAME=VALUE]... are the values for the placeholders.
%s, %q for posiitonal placeholders.%(NAME)s, %(NAME)q for named placeholders.%(NAME=DEFAULT)s, %(NAME=DEFAULT)q for placeholders with default values.%?(NAME)s, %?(NAME)q for optional placeholders.%*s, %*q for variable number of array items.%**s, %**q for variable number of key value pairs.NAME=VALUE syntax.```bash jf %s 1
jf %q 1
jf [%*s] 1 2 3
jf {%**q} one 1 two 2 three 3
jf "%q: %(value=default)q" foo value=bar
jf "{strorbool: %?(str)q %?(bool)s, optional: %?(optional)q}" str=true
jf '{1: %s, two: %q, 3: %(3)s, four: %(four=4)q, "%%": %(pct)q}' 1 2 3=3 pct=100%
```
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}"),
};