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','[email protected]'); Query OK, 1 row affected (0.19 sec) mysql> insert into JsonFormatDemo values(101,'Bob','[email protected]'); Query OK, 1 row affected (0.18 sec) mysql> insert into JsonFormatDemo values(102,'Carol','[email protected]'); Query OK, 1 row affected (0.12 sec) mysql> insert into JsonFormatDemo values(103,'Sam','[email protected]'); 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 | [email protected] | | 101 | Bob | [email protected] | | 102 | Carol | [email protected] | | 103 | Sam | [email protected] | +--------+----------+-----------------+ 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:"[email protected]"},{Name:"Bob", Email:"[email protected]"} | | 102 | {Name:"Carol", Email:"[email protected]"} | | 103 | {Name:"Sam", Email:"[email protected]"} | +--------+----------------------------------------------------------------------------+ 3 rows in set (0.00 sec)