JSON
Print a command's result as machine-readable JSON.
Usage
import { Crust } from "@crustjs/core";
import { json } from "@crustjs/extensions";
const app = new Crust("my-cli").extend(json()).command("deploy", (cmd) =>
cmd.action(({ stdout }) => {
stdout("Deploying...");
return { id: "dep_42", url: "https://example.com" };
}),
);
await app.execute();$ my-cli deploy --json
Deploying... # stderr
{"id":"dep_42","url":"https://example.com"} # stdoutjson() adds a recursive boolean --json flag. Without the flag, nothing changes. It also adds a "JSON output" section to the root command's help, man page, and generated skills, so an agent reading the CLI's documentation knows what --json prints.
Behavior
With --json, stdout carries only JSON: the command's result, or NDJSON for streaming commands. Pipes and files always get clean data.
- The Command Action's return value is printed to stdout as one line of JSON. An action that returns
undefinedprints nothing. - A failure is written to stderr as one line of JSON instead of the
Error:line. ACrustErrorprints itstoJSON()({ "code", "message", "details"? }); any other error prints{ "message": error.message }, and a thrown non-Errorvalue prints{ "message": String(value) }. No other field of an application error is read, except that@crustjs/openapi'sApiResponseErroraddsdetailswith the HTTPstatus. - The action's and Contexts'
stderr()lines, spinners, and progress go to stderr as they're written. - Cleanup that fails after a failure was already written, such as a Context whose disposal throws, or while a cancellation unwinds, is written to stderr as one more line per failed cleanup,
{"type":"cleanup","error":…}, with the same error JSON. It goes to stderr even for a generator action, so stdout keeps exactly one final line. - Exit codes are unchanged.
Text printed with stdout()
What happens to the text a command prints with stdout() depends on whether it declares .output():
| Command | Under --json, its stdout() text… | stderr |
|---|---|---|
declares .output() and returns data | is dropped, because the JSON is the same data | no duplicate text |
declares .output(), returns nothing, fails or is cancelled | is written to stderr when the command ends | the text, then any error JSON |
no .output() | moves to stderr as it's printed (live) | the text |
A command that declares .output() returns data, so its result replaces the table it prints for people:
const users = defineCommand("users", { description: "List users" }, (cmd) =>
cmd
.output(z.array(z.object({ id: z.number(), name: z.string() })))
.action(({ stdout }) => {
const rows = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Linus" },
];
stdout("ID NAME");
for (const row of rows) stdout(`${row.id} ${row.name}`);
return rows;
}),
);$ my-cli users --json
[{"id":1,"name":"Ada"},{"id":2,"name":"Linus"}] # stdout; nothing on stderrIf users returned nothing, failed, or was cancelled, its table would be written to stderr when it ended, followed by any error JSON:
$ my-cli users --json
ID NAME # stderr
1 Ada # stderr
{"message":"connection reset"} # stderrdeploy in Usage has no .output(), so Deploying... moves to stderr as it's printed. This includes output a Context writes, even while another Extension's setup pulls it. Output an Extension writes with its own stdout, such as --help, is never moved.
Write progress and instructions that must appear while the command runs (for example a login URL) with stderr() or a spinner. They're always live:
const login = defineCommand("login", { description: "Log in" }, (cmd) =>
cmd.output(z.object({ user: z.string() })).action(async ({ stderr }) => {
// stderr() is always live, so the user sees this while the command waits.
stderr("Open https://example.com/device and enter ABCD-1234");
return { user: await waitForApproval() };
}),
);stdout vs stderr
A terminal shows both streams, so a person running my-cli users --json sees everything. Pipes, >, and agents read only stdout: my-cli users --json | jq '.[0].name' and my-cli users --json > users.json get just the JSON, while stderr still goes to the terminal. That's why data goes to stdout and messages for people go to stderr.
The result must be JSON data: finite numbers, strings, booleans, null, and plain arrays and objects of them. A result JSON cannot represent exactly, such as a BigInt, a cycle, a function, -0, or a class instance like Date or Map, fails the command with exit code 1 and an error naming the problem. Convert such values before returning them, for example date.toISOString().
Generator actions
An async generator action streams newline-delimited JSON (NDJSON) on stdout instead, so a consumer reads one channel line by line:
$ tool sync --json
{"type":"event","data":{"file":"a.txt"}} # written as the action yields
{"type":"event","data":{"file":"b.txt"}}
{"type":"result","data":{"synced":2}}- Each yielded value prints as
{"type":"event","data":…}as soon as it is yielded. - The stream ends with exactly one
{"type":"result","data":…}line for thereturnvalue, even when it isundefined(the line then has nodata), or, if the command fails after the action started, one{"type":"error","error":…}line with the same error JSON as above. That failure is not also written to stderr. - Events and the result must be JSON data, as above; one that is not, including a yielded
undefined, fails the command with an error line. Only anundefinedresult is allowed. - In a command that declares
.output(), itsstdout()text is dropped once the result line carries data, and written to stderr for anundefinedresult or a failure, as above. - A failure before the action started, such as a validation error, prints stderr JSON as for any other action. A failure after the result line, such as a Context cleanup failure, also goes to stderr, so stdout never has two final lines.
An ordinary action keeps the bare result line.
Under run()
Pass { flags: { json: true } } to run():
outcome.stdoutholds the JSON result. For a generator action, it holds the event lines and the result line, but no error line.- A failure is not rendered; read it from
outcome.error. - For a command that declares
.output()and returns data,outcome.stdoutholds only the JSON andoutcome.stderrnone of itsstdout()text.
Limitations
json()sets the invocation's renderer. An application can have only one, sojson()can't be combined with another Extension that sets.renderer().- Failures before flags are bound print as plain text, because
--jsonis not yet known: unknown commands under a parent without a Command Action, and argv syntax errors such as an unknown flag or a flag missing its value.execute()prints Core's defaultError:line for them. A failure in an Extension'ssetup, such as an invalid--input, comes after binding and is JSON. - If another Extension's
onErrorhook claims a failure, it keeps that Extension's format, and a generator action's stream ends without a final line. - A cancelled invocation (exit code 130, or 143 after
SIGTERM) is not rendered, so its stream also ends without a final line.