Wing 标准库 bool 类型详解:Boolean.fromJson 从 JSON 解析布尔值

原创2026-10-12 11:02:212,000 阅读
文章标签:编程语言编译器云原生语言运行时

Wing 标准库 bool 类型详解:Boolean.fromJson 从 JSON 解析布尔值

导读

bool 是 Wing 云编程语言标准库(std)中最基础的原生类型之一。本文以标准库 API 参考文档 docs/api/04-standard-library/std/bool.md 为主线,深入讲解 std.Boolean 类及其唯一静态方法 fromJson 的签名、参数、校验行为与底层实现原理,并结合仓库源码与测试用例,帮助你掌握在 Wing 中安全地从 Json 解析出布尔值、处理类型不匹配错误、以及使用 unsafe 模式跳过校验的完整实战方案。

bool 类型在 Wing 标准库中的定位

Wing 的 std 标准库为语言核心类型提供了一组工具类。与 str、num 等类型类似,布尔值在标准库中由 Boolean 类表示,源码位于 packages/@winglang/sdk/src/std/bool.ts,其类型注解为 @wingType bool,即对应 Wing 语言中的 bool 关键字:

/**
 * Boolean
 * @wingType bool
 */
export class Boolean {
  ...
  private constructor() {}
}

从源码结构看,Boolean 类只暴露了一个静态函数 fromJson,且构造函数为私有(private constructor() {}),因此 Boolean 在 Wing 中不可直接实例化,仅作为命名空间形式的工具类使用,调用方式统一为 bool.fromJson(...)。

Boolean.fromJson 完整 API 签名

原文档给出了 fromJson 的完整签名:

bool.fromJson(json: Json, options?: JsonValidationOptions);

该签名对应源码中的实现(bool.ts):

public static fromJson(json: Json, options?: JsonValidationOptions): boolean {
  const schema = JsonSchema._createJsonSchema({
    $id: "bool",
    type: "boolean",
  } as any);
  schema.validate(json, options);
  return json as any;
}

参数说明

参数 类型 必填 说明
json Json 是(Required) 要解析出布尔值的 JSON 值,即 "to parse boolean from."
options JsonValidationOptions 否(Optional) 校验选项,目前仅支持 unsafe 一个字段

返回值为 bool(源码中为 boolean)。JsonValidationOptions 接口定义在 packages/@winglang/sdk/src/std/json.ts:

/**
 * Options for validating Json
 */
export interface JsonValidationOptions {
  /** Unsafe mode to skip validation (may lead to runtime errors) */
  readonly unsafe?: boolean;
}

前提与限制

  • fromJson 只接受 Json 类型的输入,而非任意类型。传入字面量时需要先通过 Json 字面量语法(如 Json true、Json 123)或 Json.parse(...) 构造;
  • 校验默认开启:只有值为 true / false(JSON 布尔字面量)时才解析成功,其他类型(数字、字符串、对象等)都会抛出解析错误;
  • unsafe: true 可跳过校验,但如源码注释所述"may lead to runtime errors",需谨慎使用。

基础用法示例

以下示例综合了仓库测试 tests/sdk_tests/std/bool.test.w 中的用例:

// 从 JSON 布尔字面量解析
let j = Json { enabled: true, disabled: false };

let t = bool.fromJson(j.get("enabled"));
assert(t == true);

let f = bool.fromJson(j.get("disabled"));
assert(f == false);

也可以配合 Json.parse 从字符串解析:

let t = bool.fromJson(Json.parse("true"));
assert(t == true);

let f = bool.fromJson(Json.parse("false"));
assert(f == false);

从 tests/valid/json_static.test.w 可以看到,fromJson 常与 Json.get 配合,从混合类型的 JSON 对象中按 key 取出布尔字段:

let jsonOfMany = Json {a: 123, b: "hello", c: true};
assert(bool.fromJson(jsonOfMany.get("c")));

类型不匹配时的报错行为

fromJson 默认执行严格的类型校验,非布尔值一律拒绝。测试 tests/sdk_tests/std/bool.test.w 定义了错误断言:

let PARSE_ERROR = "unable to parse bool";

let assertThrows = (expected: str, block: (): void) => {
  let var error = false;
  try {
    block();
  } catch actual {
    assert(actual.contains(expected));
    error = true;
  }
  assert(error);
};

assertThrows(PARSE_ERROR, () => {
  bool.fromJson(Json 123); // 数字不是布尔值,抛出 "unable to parse bool..."
});

对应的错误测试 tests/error/bool_from_json.test.w 展示了编译期(preflight)直接报错的场景:

let j = Json { a: 123 };

let a: bool = bool.fromJson(j.get("a"));
//                                  ^ preflight error: unable to parse number 123 as a boolean

从源码看,错误信息由 packages/@winglang/sdk/src/std/json_schema.ts 的 validate 方法生成,格式为 unable to parse {schemaId}:\n- ...,其中 schemaId 即 $id: "bool":

public validate(obj: Json, options?: JsonValidationOptions) {
  if (options?.unsafe) {
    return; // skip validation
  }
  const validator = this.validator.compile(this._rawSchema);
  const valid = validator(obj);
  if (!valid) {
    const schemaId = this._rawSchema.$id.replace("/", "");
    throw new Error(
      `unable to parse ${schemaId}:\n- ${validator.errors
        ?.map((error: any) => schemaId + error.instancePath + " " + error.message)
        .join("\n- ")}`,
    );
  }
}

源码级原理:JsonSchema + Ajv 实现类型校验

bool.fromJson 的校验逻辑并非手写,而是复用标准库统一的 JSON Schema 校验机制。整个调用链为:

  1. Boolean.fromJson 构造一个内联 schema:{ $id: "bool", type: "boolean" };
  2. 通过 JsonSchema._createJsonSchema(...) 创建校验器实例;
  3. 调用 schema.validate(json, options) 执行校验;
  4. 校验通过后直接 return json as any 作为布尔值返回。

其中 JsonSchema 内部使用 Ajv):

constructor(schema: Json) {
  this._rawSchema = schema;
  this.validator = new Ajv({ allErrors: true, allowUnionTypes: true });
}

allErrors: true 表示一次报告所有校验错误,allowUnionTypes: true 允许 union 类型声明。同一套机制也被 num.fromJson(schema 为 { $id: "num", type: "number" },见 packages/@winglang/sdk/src/std/number.ts)和 str.fromJson 等标准库类型复用,保证了所有基础类型从 JSON 解析的行为一致:默认严格校验、统一报错格式、可选用 unsafe 跳过。

使用 unsafe 跳过校验的场景

在确认 JSON 数据来源可信、或希望在解析层不做类型检查时,可以传入 options 的 unsafe: true。仓库测试 tests/valid/struct_from_json.test.w 验证了该模式:

// Testing unsafe parsing mode
str.fromJson(10, unsafe: true);
bool.fromJson(10, unsafe: true);
num.fromJson("cool", unsafe: true);

test "unsafe flight" {
  str.fromJson(10, unsafe: true);
  bool.fromJson(10, unsafe: true);
  num.fromJson("cool", unsafe: true);
}

注意:unsafe: true 只是跳过 schema 校验(validate 中直接 return),并不会做任何类型转换,返回的仍是对原始 JSON 值的引用(return json as any)。如果 JSON 值本身不是布尔值,后续对该结果做布尔运算时仍可能产生运行时错误,这正是源码注释中 "may lead to runtime errors" 的含义,因此只应在明确信任数据源时使用。

与 Json.asBool / tryAsBool 的对比

除 bool.fromJson 外,Wing 的 Json / MutJson 类型还提供实例方法 asBool() 与 tryAsBool() 用于将 JSON 元素转为布尔值,三者的差异如下:

方式 触发位置 类型不符时行为 典型适用场景
bool.fromJson(json) 静态函数 抛错 unable to parse bool... 需要严格校验且错误必须被捕获/上报
j.get("k").asBool() Json 实例方法 抛错 unable to parse ... as a boolean 已知字段为布尔、希望快速取值
j.get("k").tryAsBool() Json 实例方法 返回 undefined 字段可能不是布尔,希望安全探测

asBool 与 tryAsBool 的实现均以宏(@macro)形式定义在 packages/@winglang/sdk/src/std/json.ts:

// asBool: 非布尔时抛错
@macro ((arg) => { if (typeof arg !== "boolean") {throw new Error("unable to parse " + typeof arg + " " + arg + " as a boolean")}; return JSON.parse(JSON.stringify(arg)) })($self$)

// tryAsBool: 非布尔时返回 undefined
@macro ((arg) => { return (typeof arg === "boolean") ? JSON.parse(JSON.stringify(arg)) : undefined })($self$)

Json 字面量的使用可参考 docs/by-example/23-Json.md 中的示例(如 Json true、Json { k: true })。

实战场景:inflight 中解析远端调用返回的布尔值

bool.fromJson 最常见的实战用途,是在 inflight 代码中解析云端资源调用返回的 JSON 结果。仓库测试 tests/sdk_tests/resource/call.test.w 展示了这一模式:

pub inflight methodBool(arg: bool): bool {
  return bool.fromJson(this.backend.call("methodBool", Json [arg]));
}

这里 this.backend.call(...) 返回 Json,通过 bool.fromJson 将其还原为 Wing 的 bool 类型返回给调用方。同样的模式在该测试中还用于 num.fromJson、str.fromJson,是 Wing 中跨预检(preflight)/运行(inflight)边界传递标量值时的事实标准写法。

常见错误与排查建议

  1. 传入非 Json 字面量:bool.fromJson(true) 会编译失败,因为参数要求 Json 类型。应写为 bool.fromJson(Json true) 或先从 Json 对象中 get 取值;
  2. 校验失败错误信息定位:报错以 unable to parse bool: 开头,并列出 schema 校验详情(如 unable to parse number 123 as a boolean),据此可确认是类型不匹配而非其他运行时问题;
  3. unsafe 模式误用:unsafe: true 仅跳过校验,不改变返回值类型,对不可信数据使用可能导致后续运行时异常;
  4. 区分 fromJson 与 asBool:需要"取不到就返回 undefined"的场景应优先考虑 tryAsBool,需要强制校验并抛出明确错误的场景则使用 bool.fromJson。

进一步阅读

登录后查看全文
wing