Use Shell scripts to convert MySQL table data to json format, mysqljson
The script is as follows:
#!/bin/bashmysql -s -phello test >1.log <<EOFdesc t1;EOFlines="concat_ws(',',"count=`cat 1.log|wc -l`linenum=0while read linedo coloumname=`echo $line |awk '{print $1}'` let linenum=linenum+1 if [ $linenum -eq 1 ];then lines=$lines"concat_ws(':','{"'"'$coloumname'"'"',if("$coloumname" is null or $coloumname='','null',concat('"'"'"',$coloumname,'"'"'"')))" elif [ $linenum -eq $count ];then lines=$lines",concat_ws(':','"'"'$coloumname'"'"',if("$coloumname" is null or $coloumname='','null}',concat('"'"'"',$coloumname,'"'"'"}'))))" else lines=$lines",concat_ws(':','"'"'$coloumname'"'"',if("$coloumname" is null or $coloumname='','null',concat('"'"'"',$coloumname,'"'"'"')))" fidone < 1.logecho $lines
The data in table t1 is as follows:
mysql> select * from t1;+------+-------+| id | name |+------+-------+| 1 | || 1 | NULL || 2 | hello |+------+-------+3 rows in set (0.00 sec)
The script execution result is as follows:
concat_ws(',',concat_ws(':','{"id"',if(id is null or id='','null',concat('"',id,'"'))),concat_ws(':','"name"',if(name is null or name='','null}',concat('"',name,'"}'))))
The execution result in MySQL is as follows:
mysql> select concat_ws(',',concat_ws(':','{"id"',if(id is null or id='','null',concat('"',id,'"'))),concat_ws(':','"name"',if(name is null or name='','null}',concat('"',name,'"}')))) json_format from t1;+---------------------------+| json_format |+---------------------------+| {"id":"1","name":null} || {"id":"1","name":null} || {"id":"2","name":"hello"} |+---------------------------+3 rows in set (0.00 sec)
Tip: differences between single quotes and double quotes in shell scripts
The single quotation marks and double quotation marks in shell scripts are character string delimiters rather than character delimiters.
Single quotesIt is used to keep the literal value of all characters in the quotation marks, even if the \ and carriage return in the quotation marks are no exception, but the single quotation marks cannot appear in the string. (Note that it is all, but the single quotation mark itself cannot appear in it.).
Double quotation marksIt is used to keep the nominal value of all characters in quotation marks (carriage return is no exception), except in the following cases:
$ You can add a variable name to get the value of the variable.
Reverse quotation marks still indicate command replacement
\ $ Indicates the nominal value of $
\ 'Indicates the literal value'
The nominal value of \ "represents ".
\ Represents the literal value \
In addition to the preceding conditions, the '\' before other characters has no special meaning and only indicates the nominal value.