首先,我是一个node.js新手,我正在努力如何从postgres转换JSON数据以匹配我需要从API返回的内容。这是代码:
function readUsers(req, res, next) {
console.log('database string is ' + process.env.DB_CONNECTION_STRING);
var client = new database.Client(process.env.DB_CONNECTION_STRING);
client.connect();
console.log(req.body);
var queryString = `SELECT * from readusersbynamejson(${req.query.user_id}, '${req.query.username}', ` +
`${req.query.limit_count}, ${req.query.offset})`;
console.log("Executing: ", queryString);
client.query(queryString, function(err, result) {
console.log("query complete");
client.end();
if (err) {
console.log("error = ", err);
return next(err);
} else {
console.log("RowCount ", result.rowCount);
var rowData = [];
result.rows.map(function(row) {
try {
console.log ("Row Data: ");
console.log(row);
console.log(row.readusersbynamejson);
//console.log("Trying to parse");
//row.data = JSON.parse(row.data);
console.log("Trying to set to subnode");
return row["readusersbynamejson"];
rowData[''].push(r)
//row.
//console.log("Result: " + row);
} catch (e) {
console.log("Exception thrown");
console.log(e);
row.data = null;
return row;
}
//return newRow;
});
console.log(result.rows);
res.status(200).json({
status: 'success',
//data: result.rows[0].readusersbynamejson,
data: result.rows,
message: 'Retrieved all data'
});
}
});
}
这是postgres函数返回的内容:
{
"status": "success",
"data": [
{
"readusersbynamejson": {
"user_id": 3,
"auth_type": 1,
"status": 1,
"user_identity": "user3",
"username": "mgarcia",
"email_address": "mgarcia@gmail.com",
"phone_number": "11234567890",
"timestamp": 1537846141,
"image_reference": "",
"name": null,
"bio": null,
"friend_status": 0,
"friend_status_initiated": 0,
"post_count": 0
}
},
{
"readusersbynamejson": {
"user_id": 2,
"auth_type": 1,
"status": 1,
"user_identity": "user2",
"username": "jdoe",
"email_address": "jdoe@gmail.com",
"phone_number": "11234567890",
"timestamp": 1537846110,
"image_reference": "",
"name": null,
"bio": null,
"friend_status": 0,
"friend_status_initiated": 0,
"post_count": 0
}
}
],
"message": "Retrieved all data"
}
我真的很想从JSON中删除postgres函数名称,但是我可能需要修改它的其他部分。有人可以给我一个关于如何转换JSON的小代码段吗?我已经为此花了几个小时的时间,显然我在这里缺少一些基本的东西。
答案 0 :(得分:1)
类似的事情应该起作用:
var users = result.data.map(function(x) {
return x.readusersbynamejson;
});
在ES6中更简单:
const users = result.data.map(x => x.readusersbynamejson)