How to analyze data from the "rows" object in node.js, express.js, mysql2

I am using node, express, mysql2 packages. When I use console.log (rows), it gives me the following output:

[{"userid": "test","password": "test"}]

And here is my code:

var application_root = __dirname,
express = require("express"),
mysql = require('mysql2');
path = require("path");
var app = express();

var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123',
database: "bbsbec"
 });
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

connection.query('SELECT * from pass', function(err, rows) {
     res.json(rows);
     console.log(rows);
   });

I just want to know how I can parse this "string" object so that I can retrieve both the user ID and password.

+11
source share
3 answers

Try this (it really is):

   connection.query('SELECT * from pass', function(err, rows) {
     res.json(rows);

     var user = rows[0].userid;
     var password= rows[0].password;

   });
+15
source
[{"userid": "test","password": "test"}]

This is Arrayof Objects. So: first loop over the array to get one object and then retrieve its properties:

for (var i = 0; i < rows.length; i++) {
    var row = rows[i];
    console.log(row.userid);
}
+20
source

 connection.query('SELECT * from pass', function(err, rows) {
      data = rows[0];
     let user = data.userid;
     let password= data.password;
     res.json(rows);

   });
Run codeHide result

0
source

Source: https://habr.com/ru/post/1531595/


All Articles