本节中列出的函数由组件元素组成 JSON 值。The functions listed in this section compose JSON values from component elements.
JSON_ARRAY([val[, val] ...])JSON_ARRAY([val[,val] ...])评估一个(可能为空的)值列表,并返回一个包含这些值的 JSON 数组。Evaluates a (possibly empty) list of values and returns a JSON array containing those values.
mysql>
SELECT JSON_ARRAY(1, "abc", NULL, TRUE, CURTIME());+---------------------------------------------+ | JSON_ARRAY(1, "abc", NULL, TRUE, CURTIME()) | +---------------------------------------------+ | [1, "abc", null, true, "11:30:24.000000"] | +---------------------------------------------+JSON_OBJECT([key,val[,key,val] ...])计算一个(可能为空的)键值对列表,并返回包含这些键值对的 JSON 对象。如果任意键名为
NULL或参数数量为奇数,会产生错误。Evaluates a (possibly empty) list of key-value pairs and returns a JSON object containing those pairs. An error occurs if any key name isNULLor the number of arguments is odd.mysql>
SELECT JSON_OBJECT('id', 87, 'name', 'carrot');+-----------------------------------------+ | JSON_OBJECT('id', 87, 'name', 'carrot') | +-----------------------------------------+ | {"id": 87, "name": "carrot"} | +-----------------------------------------+通过用双引号字符包裹字符串并转义内部的引号和其他字符,将字符串作为 JSON 值引用,然后将结果作为
utf8mb4字符串返回。如果参数为NULL,则返回NULL。Quotes a string as a JSON value by wrapping it with double quote characters and escaping interior quote and other characters, then returning the result as autf8mb4string. ReturnsNULLif the argument isNULL.此函数通常用于生成一个有效的 JSON 字符串字面值,以便包含在 JSON 文档中。This function is typically used to produce a valid JSON string literal for inclusion within a JSON document.
根据表 14.23,“JSON_UNQUOTE() 特殊字符转义序列”中显示的转义序列,一些特殊字符使用反斜杠进行转义。Certain special characters are escaped with backslashes per the escape sequences shown in Table 14.23, “JSON_UNQUOTE() Special Character Escape Sequences”.
mysql>
SELECT JSON_QUOTE('null'), JSON_QUOTE('"null"');+--------------------+----------------------+ | JSON_QUOTE('null') | JSON_QUOTE('"null"') | +--------------------+----------------------+ | "null" | "\"null\"" | +--------------------+----------------------+ mysql>SELECT JSON_QUOTE('[1, 2, 3]');+-------------------------+ | JSON_QUOTE('[1, 2, 3]') | +-------------------------+ | "[1, 2, 3]" | +-------------------------+
你也可以通过将其他类型的值转换为JSON类型来获取 JSON 值,方法是使用CAST(value AS
JSON);更多信息请参见在 JSON 与非 JSON 值之间转换。You can also obtain JSON values by casting values of other types
to the JSON type using
CAST(; see
Converting between JSON and non-JSON values, for more
information.value AS
JSON)
有两个用于生成 JSON 值的聚合函数。JSON_ARRAYAGG() 将结果集作为单个 JSON 数组返回,JSON_OBJECTAGG() 将结果集作为单个 JSON 对象返回。更多信息,请参见 第 14.19 节,“聚合函数”。Two aggregate functions generating JSON values are available.
JSON_ARRAYAGG() returns a result
set as a single JSON array, and
JSON_OBJECTAGG() returns a result
set as a single JSON object. For more information, see
Section 14.19, “Aggregate Functions”.