Lit Aiy Lit Aiy - 3 months ago 15
JSON Question

Adding parent key to this json output

I am using restify module on node.js to build a REST API server.

I have this simple API using restify.

var api_get_sample = function (app, url_name) {
function respond(req, res, next) {
var door = req.query.door;
var connection = custom_mysql.getMySQL_connection();
var query_str =
"SELECT XXX, YYY " +
"FROM TABLE_X " +
"WHERE door = ? "
;
var query_var = [door];
var query = connection.query(query_str, query_var, function (err, rows, fields) {
//if (err) throw err;
if (err) {
console.log(err);
}
else {
res.send(rows);
}
}); //var query = connection.query(query_str, function (err, rows, fields) {
return next();
}

app.get(url_path, url_name);
};


It outputs a json which looks like this;

[{
"ID": 1,
"NAME": "James",

},
{
"ID": 2,
"NAME": "John",

}]


I would like to add a parent key to the json output such that it looks like this;

["Parent_key_added": {
{
"ID": 1,
"NAME": "James",

},
{
"ID": 2,
"NAME": "John",

}
}]


How do I manipulate the variable
rows
which is actually an array of RowDataPacket to add the key
Parent_key_added
?

Answer
else {
            res.send({ parent_key: rows});
        }
Comments