10

I have a MySQL column of json type. In there, a dict like JSON object is stored. Now, I want to extract the values from this JSON object and create a JSON array.

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:)

CREATE TABLE `json_objs` (
  `json_col` json DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
marekful
  • 14,986
  • 6
  • 37
  • 59
Yuki Inoue
  • 3,569
  • 5
  • 34
  • 53

2 Answers2

9

You can use the -> operator as in the expression column -> path as follows:

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

marekful
  • 14,986
  • 6
  • 37
  • 59
4

Other than -> operator, you can also use the Json_Extract() function:

Schema (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

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

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

View on DB Fiddle

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
  • I was faster and you copied code from my answer. However, I upvoted yours because you showed a slightly different alternative :) – marekful Nov 28 '18 at 10:10
  • @marekful Thanks for the fiddle. I was lazy to create a fiddle; so pouched on your fiddle :P – Madhur Bhaiya Nov 28 '18 at 10:11