How to create JSON format with group-concat in MySQL?


You can create JSON format using group_concat() function from MySQL. The syntax is as follows −

SELECT yourColumnName1,
   GROUP_CONCAT(CONCAT('{anytName:"', yourColumnName, '",
anyName:"',yourColunName,'"}')) anyVariableName
   from yourTableName
group by yourColumnName1;

To understand the above syntax, let us first create a table. The query to create a table is as follows −

mysql> create table JsonFormatDemo
   -> (
   -> UserId int,
   -> UserName varchar(100),
   -> UserEmail varchar(100)
   -> );
Query OK, 0 rows affected (0.99 sec)

Insert some records in the table using insert command. The query to insert record is as follows −

mysql> insert into JsonFormatDemo values(101,'John','John@gmail.com');
Query OK, 1 row affected (0.19 sec)

mysql> insert into JsonFormatDemo values(101,'Bob','John@gmail.com');
Query OK, 1 row affected (0.18 sec)

mysql> insert into JsonFormatDemo values(102,'Carol','Carol@gmail.com');
Query OK, 1 row affected (0.12 sec)

mysql> insert into JsonFormatDemo values(103,'Sam','Sam@gmail.com');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from JsonFormatDemo;

Output

+--------+----------+-----------------+
| UserId | UserName | UserEmail       |
+--------+----------+-----------------+
|    101 | John     | John@gmail.com  |
|    101 | Bob      | John@gmail.com  |
|    102 | Carol    | Carol@gmail.com |
|    103 | Sam      | Sam@gmail.com   |
+--------+----------+-----------------+
4 rows in set (0.00 sec)

The query to create a JSON format with the help of group_concat() function −

mysql> select UserId,
   -> GROUP_CONCAT(CONCAT('{Name:"', UserName, '", Email:"',UserEmail,'"}')) JsonFormat
   -> from JsonFormatDemo
   -> group by UserId;

Output

+--------+----------------------------------------------------------------------------+
| UserId | JsonFormat                                                                 |
+--------+----------------------------------------------------------------------------+
|    101 | {Name:"John", Email:"John@gmail.com"},{Name:"Bob", Email:"John@gmail.com"} |
|    102 | {Name:"Carol", Email:"Carol@gmail.com"}                                    |
|    103 | {Name:"Sam", Email:"Sam@gmail.com"}                                        |
+--------+----------------------------------------------------------------------------+
3 rows in set (0.00 sec)

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements