将SQL结果转换为JSON的正确方法

时间:2017-11-26 07:16:48

标签: mysql sql json node.js

我正在使用nodejs创建API。 API接受请求并以JSON

响应

例如: 我的数据库中有一个表QUESTION,因此对端点http://localhost/table/question的GET请求将以JSON格式输出表。

但是执行JOINS时出现问题

考虑表QUESTION和CHOICE。一个问题有许多选择(答案),他们的加入将是

表:

enter image description here

我正在尝试转换为类似的东西

{  
   "0":{  
      "QUESTION":"If Size of integer pointer is 4 Bytes what is size of float pointer ?",
      "OPTION":{  
         "A":"3 Bytes",
         "B":"32 Bits",
         "C":"64 Bits",
         "D":"12 Bytes"
      }
   },
   "1":{  
      "QUESTION":"Which one is not a SFR",
      "OPTION":{  
         "A":"PC",
         "B":"R1",
         "C":"SBUF"
      }
   },
   "2":{  
      "QUESTION":"What is Size of DPTR in 8051",
      "OPTION":{  
         "A":"16 Bits",
         "B":"8 Bytes",
         "C":"8 Bits"
      }
   },
   "3":{  
      "QUESTION":"Is to_string() is valid builtin function prior to c++11 ? ",
      "OPTION":{  
         "A":"Yes",
         "B":"No"
      }
   }
}

显而易见的解决方案是使用JOIN解析查询并将其转换为JSON。 有没有更有效的方法呢?

1 个答案:

答案 0 :(得分:1)

在MySQL中,您可以使用group_concat

实现此目的

表名,字段名等都是纯粹的幻想: - )

select
    q.text as question,
    group_concat(answer.label, ';;;') as labels,
    group_concat(answer.text, ';;;') as answers
from
    question as q
    join answer as a on a.quesion = q.id
group by
    q.text

然后在你的应用程序(nodejs)

let resultRows = callSomeFunctionsThatReturnesAllRowsAsArray();
let properStructure = resultRows.map(row => {
    let texts = row.answers.split(';;;');
    return {
        question: row.question,
        options: row.labels.split(';;;').map((label, index) => {label: label, answer: texts[index]});
    }
});