从mysql json列中提取json对象的值作为数组

apeeds0o  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(456)

我有一个json类型的mysql列。其中存储了类似dict的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
qhhrdooz

qhhrdooz1#

-> 操作员,您也可以使用 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视图

wdebmtf2

wdebmtf22#

你可以用 -> 表达式中的运算符 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-列路径

相关问题