How to read MySQL data as JSON

吃可爱长大的小学妹 提交于 2020-01-21 10:31:35

问题


I have a database table like this:

Then I want to read data as json object like this:

{
   "date_time":"02102019",
   "ma_vi_tri":
   {
       "1a":222,
       "0a":111,
       "2a":333
   }
 }

I use this SQL command like this:

MariaDB [mqtt]> SELECT json_object('date_time',date_time,'ma_vi_tri',ma_vi_tri, 'PH', PH) FROM PH where date_time='02102019';

But result output not like I wish.

Thank you in advance.


回答1:


One option (be careful with performance problems):

SELECT
  CONCAT(
    '{"date_time": "', `date_time`, '", "ma_vi_tri": ',
    REPLACE(
      GROUP_CONCAT(
        JSON_OBJECT(`ma_vi_tri`, `PH`)
      ),
    '},{',
    ', '
    ),
    '}'
  ) `JSON`
FROM
  `PH`
WHERE
  `date_time` = '02102019'
GROUP BY
  `date_time`;

See dbfiddle.




回答2:


You can create a multi dimensional array and use json_encode

Example:

$ma_vi_tri_arr['1a'] = "222";
$ma_vi_tri_arr['0a'] = "111";
$ma_vi_tri_arr['2a'] = "333";

$result['date_time'] = "02102019";
$result['ma_vi_tri'] = $ma_vi_tri_arr;

echo(json_encode($result));


来源:https://stackoverflow.com/questions/58231149/how-to-read-mysql-data-as-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!