語法
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 |
瀏覽器相容性
載入中…