Search code examples
mysqljsonstored-proceduresmultidimensional-array

MySQL Stored Proc build multidimensional JSON


I have table with the following data structure:

name | age |     date    | value
---------------------------------
John | 20  |  2020-01-01 |   5
Peter| 21  |  2020-01-02 |  6.5
John | 26  |  2019-02-26 |  1.8
John | 20  |  2029-10-13 |  0.7
Peter| 47  |  2020-01-18 | 11.3
Peter| 21  |  2020-02-01 | 41.7
John | 20  |  2020-01-22 |   4

I want only by Mysql 5.5.5 Stored Proc(no json aggregate functions) to get result like this:

{
  "John (20)" : {
    ["2020-01-01", 5],
    ["2029-10-13", 0.7],
    ["2029-10-13", 4]
  },
  "John (26)" : {
    ["2019-02-26", 1.8]
  },
  "Peter (21)" : {
    ["2020-01-02", 6.5],
    ["2020-02-01", 41.7],
  },
  "Peter (47)" : {
    ["2020-01-18", 11.3]
  }
}

And can't figure out how to make it. Only getting flat json....

   select concat('[', group_concat(
   '{"name":"',`name`,'",',
   '"age":"',`age`,'",',
   '"date":"',`date`,'",',
   '"value":',`value`, '}' separator ','), ']') from `data`

Solution

  • One option:

    SELECT
      CONCAT(
        '{',
        GROUP_CONCAT(
          CONCAT(
            `der`.`name_age`,
            ': {',
            `der`.`date_value`,
            '}'
          )
          SEPARATOR ', '),
        '}'
      ) `json_result`
    FROM (
      SELECT
        CONCAT(
          '"',
          `name`,
          ' (', `age`, ')"'
        ) `name_age`,
        GROUP_CONCAT(
          CONCAT(
            '["',
            `date`,
            '", ',
            `value`,
            ']'
          )
          SEPARATOR ', ') `date_value`
      FROM
        `data`
      GROUP BY
        `name`, `age`
    ) `der`;
    

    See dbfiddle.