JSON.rawJSON()

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

JSON.rawJSON() 静态方法创建一个包含一段 JSON 文本的 "原始 JSON" 对象。当序列化为 JSON 时,原始 JSON 对象将被视为已经是一段 JSON。此文本必须是有效的 JSON。

¥The JSON.rawJSON() static method creates a "raw JSON" object containing a piece of JSON text. When serialized to JSON, the raw JSON object is treated as if it is already a piece of JSON. This text is required to be valid JSON.

语法

¥Syntax

js
JSON.rawJSON(string)

参数

¥Parameters

string

JSON 文本。必须是表示原始值的有效 JSON。

返回值

¥Return value

一个对象,可用于创建与 string 提供的内容完全相同的 JSON 文本,字符串本身不带引号。该对象 null 原型机被冻结 (因此它永远不会通过任何类型的基元转换意外序列化为常规对象),以及以下属性:

¥An object that can be used to create JSON text with the exact same content as the string provided, without quotes around the string itself. This object has null prototype and is frozen (so it never gets accidentally serialized as a regular object by any kind of primitive conversion), and the following property:

rawJSON

提供了原始 JSON string

此外,它还有一个 私有属性 将自己标记为原始 JSON 对象。这使得它可以被 JSON.stringify()JSON.isRawJSON() 识别。

¥Furthermore, it has a private property that marks itself as a raw JSON object. This allows it to be identified by JSON.stringify() and JSON.isRawJSON().

例外情况

¥Exceptions

SyntaxError

如果 string 不是有效的 JSON,或者它表示对象或数组,则抛出该异常。

描述

¥Description

原始 JSON 对象可以被视为不可变的原子数据结构,就像任何类型的 primitive。它不是常规对象,除了原始 JSON 文本之外不包含任何数据。它用于将 "pre-serialize" 数据格式化为 JSON.stringify 本身由于各种原因无法产生的格式。最典型的用例是浮点数精度损失问题。例如:

¥A raw JSON object can be seen as an immutable, atomic data structure like any kind of primitive. It is not a regular object and it contains no data other than the raw JSON text. It is used to "pre-serialize" data to formats that JSON.stringify itself cannot produce for various reasons. The most typical use case is the floating point number loss of precision problem. For example:

js
JSON.stringify({ value: 12345678901234567890 });
// {"value":12345678901234567000}

该值不再完全等于原始数字!这是因为 JavaScript 对所有数字都使用浮点表示,因此它无法准确表示所有整数。当 JavaScript 解析数字文字 12345678901234567890 时,它本身已经四舍五入为最接近的可表示数字。

¥The value is not exactly equivalent to the original number any more! This is because JavaScript uses floating point representation for all numbers, so it cannot represent all integers exactly. The number literal 12345678901234567890 itself is already rounded to the nearest representable number when it is parsed by JavaScript.

如果没有 JSON.rawJSON,就无法告诉 JSON.stringify 生成数字 12345678901234567000,因为根本没有相应的 JavaScript 数字值。使用原始 JSON,你可以直接告诉 JSON.stringify() 特定值应字符串化为:

¥Without JSON.rawJSON, there is no way to tell JSON.stringify to produce the number literal 12345678901234567000, because there is simply no corresponding JavaScript number value. With raw JSON, you can directly tell JSON.stringify() what a particular value should be stringified as:

js
const rawJSON = JSON.rawJSON("12345678901234567890");
JSON.stringify({ value: rawJSON });
// {"value":12345678901234567890}

有关更完整的示例,请参阅 无损数字序列化

¥For a more complete example of this, see Lossless number serialization.

请注意,虽然我们向 JSON.rawJSON() 传递了一个字符串,但它在最终的 JSON 中仍然变成了一个数字。这是因为该字符串代表逐字 JSON 文本。如果你想序列化一个字符串,你应该使用 JSON.rawJSON() 和引号括起来的字符串值:

¥Note that although we passed a string to JSON.rawJSON(), it still becomes a number in the final JSON. This is because the string represents the verbatim JSON text. If you want to serialize a string, you should use JSON.rawJSON() with a quotes-enclosed string value:

js
const rawJSON = JSON.rawJSON('"Hello world"');
JSON.stringify({ value: rawJSON });
// {"value":"Hello world"}

JSON.rawJSON 允许你插入任意 JSON 文本,但不允许你创建无效的 JSON。JSON.rawJSON() 也不允许 JSON 语法不允许的任何内容:

¥JSON.rawJSON allows you to insert arbitrary JSON text, but does not allow you to create invalid JSON. Anything that was not permitted by the JSON syntax is not permitted by JSON.rawJSON() either:

js
const rawJSON = JSON.rawJSON('"Hello\nworld"'); // Syntax error, because line breaks are not allowed in JSON strings

此外,你不能使用 JSON.rawJSON() 创建 JSON 对象或数组。

¥Furthermore, you cannot use JSON.rawJSON() to create JSON objects or arrays.

示例

¥Examples

使用 JSON.rawJSON() 创建不同类型的 JSON 表达式

¥Using JSON.rawJSON() to create JSON expressions of different types

js
const numJSON = JSON.rawJSON("123");
const strJSON = JSON.rawJSON('"Hello world"');
const boolJSON = JSON.rawJSON("true");
const nullJSON = JSON.rawJSON("null");

console.log(
  JSON.stringify({
    age: numJSON,
    message: strJSON,
    isActive: boolJSON,
    nothing: nullJSON,
  }),
);

// {"age":123,"message":"Hello world","isActive":true,"nothing":null}

但是,你不能使用 JSON.rawJSON() 创建 JSON 对象或数组:

¥However, you cannot use JSON.rawJSON() to create JSON objects or arrays:

js
const arrJSON = JSON.rawJSON("[1, 2, 3]");
const objJSON = JSON.rawJSON('{"a": 1, "b": 2}');
// SyntaxError

使用 JSON.rawJSON() 创建转义字符串文字

¥Using JSON.rawJSON() to create escaped string literals

除了数字之外,只有另一种类型在 JavaScript 值和 JSON 文本之间没有一一对应的关系:字符串。当字符串序列化为 JSON 时,除了 JSON 字符串文字中不合法的代码点(例如换行符)之外,所有代码点都按字面打印:

¥Apart from numbers, there is only one other type that does not have a one-to-one correspondence between JavaScript values and JSON text: strings. When strings are serialized to JSON, all code points, other than those that are not legal inside JSON string literals (such as line breaks), are printed literally:

js
console.log(JSON.stringify({ value: "\ud83d\ude04" })); // {"value":"😄"}

这可能并不理想,因为该字符串的接收者可能会以不同的方式处理 Unicode。为了提高互操作性,你可以显式指定要使用转义序列序列化的字符串:

¥This may not be desirable, because the receiver of this string may handle Unicode differently. To improve interoperability, you can explicitly specify the string to be serialized with escape sequences:

js
const rawJSON = JSON.rawJSON('"\\ud83d\\ude04"');
const objStr = JSON.stringify({ value: rawJSON });
console.log(JSON.parse(objStr).value); // 😄

请注意,rawJSON 中的双反斜杠实际上代表单个斜杠字符,因此 JSON 文本如下所示:

¥Note that the double backslashes in the rawJSON actually represents a single slash character, so the JSON text looks like:

{"value":"\ud83d\ude04"}

规范

No specification found

No specification data found for javascript.builtins.JSON.rawJSON.
Check for problems with this page or contribute a missing spec_url to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看