7

我有一个 json 类型的 MySQL 列。在那里,存储了一个类似 JSON 对象的字典。现在,我想从这个 JSON 对象中提取值并创建一个 JSON 数组。

我怎样才能做到这一点?

示例查询

with json_objs(json_col) as (
  select CAST('{"key1": "value1", "key2": "value2"}' AS JSON)
  UNION ALL
  select CAST('{"key3": "value3", "key4": "value4"}' AS JSON)
)
select SOME_EXPR_I_CAN_T_FIGURE_OUT from json_objs

预期结果

+----------------------+
| resulting_column     |
+----------------------+
| ["value1", "value2"] |
| ["value3", "value4"] |
+----------------------+

(如果需要表 DDL:)

CREATE TABLE `json_objs` (
  `json_col` json DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
4

2 回答 2

9

您可以->在表达式中使用运算符,column -> path如下所示:

create table table1 (
   json_dict JSON
);

insert into table1 values('{"ak":"av","bk":"bv"}');
insert into table1 values('{"ak2":"av2","bk2":"bv2"}');

select * from table1;
+------------------------------+
| json_dict                    |
+------------------------------+
| {"ak": "av", "bk": "bv"}     |
| {"ak2": "av2", "bk2": "bv2"} |
+------------------------------+
2 rows in set (0.00 sec)

select json_dict->"$.*" from table1;
+------------------+
| json_dict->"$.*" |
+------------------+
| ["av", "bv"]     |
| ["av2", "bv2"]   |
+------------------+
2 rows in set (0.00 sec)

https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_json-column-path

于 2018-11-28T10:03:03.303 回答
2

除了->运算符,您还可以使用以下Json_Extract()功能:

架构 (MySQL v8.0)

create table table1 (
   json_dict JSON
);

insert into table1 values('{"ak":"av","bk":"bv"}');
insert into table1 values('{"ak2":"av2","bk2":"bv2"}');

查询 #1

select JSON_EXTRACT(json_dict, '$.*') from table1;

| JSON_EXTRACT(json_dict, '$.*') |
| ------------------------------ |
| ["av", "bv"]                   |
| ["av2", "bv2"]                 |

在 DB Fiddle 上查看

于 2018-11-28T10:07:37.427 回答