简体   繁体   English

从MySQL JSON列中将JSON对象的值提取为数组

[英]Extract JSON object's values as array from MySQL JSON column

I have a MySQL column of json type. 我有一个json类型的MySQL列。 In there, a dict like JSON object is stored. 在那里,存储了像JSON对象这样的字典。 Now, I want to extract the values from this JSON object and create a JSON array. 现在,我想从这个JSON对象中提取值并创建一个JSON数组。

How can I achieve this? 我怎样才能做到这一点?

Example Query 示例查询

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

Expected result 预期结果

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

(If table DDL is desired:) (如果需要表DDL :)

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

You can use the -> operator as in the expression column -> path as follows: 您可以在表达式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 https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_json-column-path

Other than -> operator, you can also use the Json_Extract() function: 除了->运算符,您还可以使用Json_Extract()函数:

Schema (MySQL v8.0) 架构(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"}');

Query #1 查询#1

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

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

View on DB Fiddle 查看DB小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM