MySQL 如何在node.js中将mysql查询的结果输出为json文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26381329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:07:32  来源:igfitidea点击:

How to output result of a mysql query as a json file in node.js

mysqljsonnode.js

提问by Rawan Hamdi

What i have her is this

我有她的是这个

app.post('/login', function (req, res){
  connection.connect();
  email = req.body.email;
  password = req.body.password;
  if(email && password ) {
    console.log(email);
    console.log(password);
   // connection.query('SELECT username FROM user WHERE email =? and password = ?', [email, password], 
   // function (error, rows, fields) { 
    connection.query('SELECT * FROM user ', 
    function (error, rows, fields) {
      var str='';
      for (var i = 0;i < rows.length; i++) {
        str = str + rows[i].username;
        res.end(str);
      }
      connection.end(); 
    }); 
  }
});

so instead of just displaying the result i want it to be something like this:

所以我希望它不是仅仅显示结果,而是这样的:

{
 "username": "ABC",
 "username": "DEF",
 "username": "HIJ"
}

回答by Mike Perrenoud

The first problem is you're not actually building the object you want. The second problem is you're not building an array of them. Finally, you need to convert that array into JSON if the resobject doesn't have something like res.json.

第一个问题是您实际上并没有构建您想要的对象。第二个问题是您没有构建它们的数组。最后,如果res对象没有类似res.json.

var objs = [];
for (var i = 0;i < rows.length; i++) {
    objs.push({username: rows[i].username});
}
connection.end();
res.end(JSON.stringify(objs));

回答by Shivkanth

With Express 4.x, the output rows from mysql db is in json format.

使用 Express 4.x,mysql db 的输出行采用 json 格式。

For example, look at this

例如,看看这个

sqlConnect.connection.query('SELECT * from users', function(err, rows, fields){
  if (err)
  {
   console.log("Querying error");
  }
  else
  {
   console.log(rows);
  }
  sqlConnect.connection.end();
 });
});

The output is of the form

输出的形式

[ RowDataPacket {
    id: 1,
    username: 'shivkanth',
    password: '1q2w3e4r',
    verified: 0 } ]

So now you can get the individual values using the . operator. For example, console.log(rows[0].username) will log the value 'shivkanth'

所以现在您可以使用 . 操作员。例如,console.log(rows[0].username) 将记录值 'shivkanth'