命令字典
Slash 命令、CLI 子命令、Hook 事件、启动参数的字典与演进史。
Slash 命令、CLI 子命令、Hook 事件、启动参数的字典与演进史。
获取与JSON Schema匹配的验证JSON输出
--json-schema <schema>claude -p --json-schema '{"type":"object",...}' "query"--json-schema 是 Claude Code CLI 的启动 flag,只在 print mode(-p) 下可用。官方 CLI reference 的描述是:agent 完成整个 workflow 后,返回与给定 JSON Schema 匹配、经过验证的 JSON 输出。
--output-format json 使用时,响应里带有请求元数据(session ID、usage 等),符合 schema 的对象放在 structured_output 字段中。claude -p --json-schema '{"type":"object","properties":{...}}' "query"
官方 headless 文档的完整示例(提取函数名,返回字符串数组):
claude -p "Extract the main function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'
用 jq 取出结构化结果:
claude -p "Extract function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
| jq '.structured_output'
| flag | 关系 |
|---|---|
-p / --print | 必需。CLI reference 标明 "print mode only" |
--output-format json | headless 文档的取用方式:structured_output 字段出现在 JSON 响应里 |
--bare | headless 文档将其列为脚本和 SDK 调用的推荐模式,官方 headless 页的 CI 示例也建议加上,可以让不同机器上的结果一致(跳过 hooks、plugins、MCP、CLAUDE.md 等自动发现) |
--allowedTools 等 | 未见文档写明与 --json-schema 冲突。schema 输出发生在 agent 完成 workflow 之后 |
官方文档没有列出与 --json-schema 互斥的具体 flag。
截至当前可访问的官方文档,--json-schema 未见对应的 env var 或 settings.json 字段。SDK 侧的等价选项是 outputFormat(TypeScript)/ output_format(Python),取值为 { type: "json_schema", schema: ... }。
| 约束 | 原因 / 来源 |
|---|---|
仅 print mode(-p) | CLI reference 明确标注 |
schema 无效时启动即报错退出,输出 Error: --json-schema is not a valid JSON Schema 及校验器诊断 | headless 文档 |
format 关键字(如 "format": "email")被接受,但只当 annotation,不强制校验 | CLI reference / headless 文档 |
| SDK 用 JSON Schema draft-07 校验,声明更新版本的 schema 会被拒绝 | Agent SDK 文档(该段针对 SDK 与 Zod,CLI flag 是否同样如此文档未单独说明) |
支持基本类型、enum、const、required、嵌套对象、$ref | Agent SDK 文档;完整清单与限制见其链接的 API 文档 "JSON Schema limitations" |
structured_output 的普通文本;包含 format 的 schema 还会被误判为无效(headless 文档、Agent SDK 文档和 changelog 引述均有记载)。在旧版本上跑脚本,不能假设"没报错就是拿到了结构化结果"。format 不会被强制:"format": "email" 之类不会阻止不合规的字符串,需要在调用方自行校验。success 不等于有 structured_output:Agent SDK 文档指出,result 的 subtype 可能是 success 却没有 structured_output(例如运行完成但 agent 没有产出结构化输出),应视为失败。脚本里要检查字段是否存在,而不只是看退出状态。error_max_structured_output_retries。文档说明其成因包括 schema 过复杂、任务本身含糊,也可能是 model fallback 撤回了已完成的输出且没有成功重试;可查看 result 上的 errors 列表区分。claude -p ... --output-format json --json-schema ... | jq '.structured_output',把结果直接交给下游工具(headless 文档示例)。--bare,让不同机器上的结果一致(跳过本机 hooks、plugins、MCP、CLAUDE.md 等自动发现);脚本可按退出码分支(0 为成功,非零为运行失败)。