跳到主要内容
版本: 最新版本-3.5

json_each

将 JSON 对象的外部元素展开为两列中保存的键值对集,并返回一个表,该表包含每个元素的行。

提示

所有 JSON 函数和运算符都列在导航栏和概述页面

通过生成列加速您的查询

语法

json_each(json_object_expr)

参数

json_object_expr:表示 JSON 对象的表达式。该对象可以是 JSON 列,也可以是由 JSON 构造函数(例如 PARSE_JSON)生成的 JSON 对象。

返回值

返回两列:一列名为 key,另一列名为 value。 key 列存储 VARCHAR 值,value 列存储 JSON 值。

使用说明

json_each 函数是一个表函数,它返回一个表。 返回的表是一个结果集,由多行组成。 因此,必须在 FROM 子句中使用横向连接将返回的表连接到原始表。 横向连接是强制性的,但 LATERAL 关键字是可选的。 json_each 函数不能在 SELECT 子句中使用。

示例

-- A table named tj is used as an example. In the tj table, the j column is a JSON object.
mysql> SELECT * FROM tj;
+------+------------------+
| id | j |
+------+------------------+
| 1 | {"a": 1, "b": 2} |
| 3 | {"a": 3} |
+------+------------------+

-- Expand the j column of the tj table into two columns by key and value to obtain a result set that consists of multiple rows. In this example, the LATERAL keyword is used to join the result set to the tj table.

mysql> SELECT * FROM tj, LATERAL json_each(j);
+------+------------------+------+-------+
| id | j | key | value |
+------+------------------+------+-------+
| 1 | {"a": 1, "b": 2} | a | 1 |
| 1 | {"a": 1, "b": 2} | b | 2 |
| 3 | {"a": 3} | a | 3 |
+------+------------------+------+-------+