JSON.isRawJSON()

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

JSON.isRawJSON() 静态方法用于测试某个值是否是由 JSON.rawJSON() 返回的对象。

语法

js
JSON.isRawJSON(value)

参数

value

要测试的值。

返回值

如果 value 是由 JSON.rawJSON() 创建的,则返回 true;否则返回 false

描述

“原始 JSON”对象在序列化为 JSON 时,会被视为其本身就是一段 JSON。此外,由于 JSON.rawJSON() 的工作方式,原始 JSON 被保证是语法有效的 JSON。有关原始 JSON 对象的结构和行为的更多信息,请参阅 JSON.rawJSON()。此方法允许其他序列化库为原始 JSON 对象实现与 JSON.stringify() 类似的行为。

示例

使用 JSON.isRawJSON()

以下示例演示了如何使用 JSON.isRawJSON() 来测试一个对象是否由 JSON.rawJSON() 返回。它实现了一个自定义序列化器,用于将数据序列化为类似 YAML 的格式。

js
function mySerializer(value, indent = "") {
  if (typeof value !== "object" || value === null) {
    return JSON.stringify(value);
  }
  if (JSON.isRawJSON(value)) {
    return value.rawJSON;
  }
  const subIndent = `${indent}  `;
  if (Array.isArray(value)) {
    return `- ${value.map((v) => mySerializer(v, subIndent)).join(`\n${indent}- `)}`;
  }
  return Object.entries(value)
    .map(([key, value]) => {
      const subValue = mySerializer(value, subIndent);
      if (subValue.includes("\n")) {
        return `${key}:\n${subIndent}${subValue}`;
      }
      return `${key}: ${subValue}`;
    })
    .join(`\n${indent}`);
}

console.log(
  mySerializer({
    name: "Josh",
    userId: JSON.rawJSON("12345678901234567890"),
    friends: [
      { name: "Alice", userId: JSON.rawJSON("9876543210987654321") },
      { name: "Bob", userId: JSON.rawJSON("56789012345678901234") },
    ],
  }),
);

// name: "Josh"
// userId: 12345678901234567890
// friends:
//   - name: "Alice"
//     userId: 9876543210987654321
//   - name: "Bob"
//     userId: 56789012345678901234

如果在上面的示例中,userId 值不是由 JSON.rawJSON() 创建,而是直接作为数字传递,那么由于 JS 浮点精度限制,我们会立即损失精度。

js
console.log(
  mySerializer({
    name: "Josh",
    userId: 12345678901234567890,
    friends: [
      { name: "Alice", userId: 9876543210987654321 },
      { name: "Bob", userId: 56789012345678901234 },
    ],
  }),
);

// name: "Josh"
// userId: 12345678901234567000
// friends:
//   - name: "Alice"
//     userId: 9876543210987655000
//   - name: "Bob"
//     userId: 56789012345678900000

规范

规范
JSON.parse 源代码访问
# sec-json.israwjson

浏览器兼容性

另见