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

我正在使用nodejs创build一个API。 API接受请求并以JSON响应

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

但是,执行JOINS时出现问题

考虑表问题和select。 一个问题有很多select(答案),他们的join将是

表:

在这里输入图像描述

我正试图转换成这样的东西

{ "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" } } } 

显而易见的解决scheme是使用JOINparsing查询并将其转换为JSON。 有没有更有效的方法来做到这一点?

在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]}); } });