json - Nodejs如何将postgresql查询结果的行转换为json数组?
问题描述
我从 postgreSQL 数据库得到以下查询结果,然后我想发送应该只有部分的响应:行到客户端。我需要响应是 json 格式,所以你能告诉我如何将查询结果:行转换为 json 数组吗?
Result {
command: 'SELECT',
rowCount: 1,
oid: NaN,
rows:
[ anonymous {
uid: 23,
name: 'Test Human',
email: 'test@example.com',
password: 'test',
created: 2018-08-24T09:44:19.659Z,
terminited: null }
anonymous {
uid: 12,
name: 'Test Animal',
email: 'ani@example.com',
password: 'hello',
created: 2018-08-24T09:44:19.659Z,
terminited: null }
],
fields:
...
_parsers:
[ [Function: parseInteger],
[Function: noParse],
[Function: noParse],
[Function: noParse],
[Function: parseDate],
[Function: parseDate] ],
RowCtor: [Function: anonymous],
rowAsArray: false,
_getTypeParser: [Function: bound ] }
Node.js 代码:
// router for get friends information
router.get("/getfriends", (req, res) => {
const uid = req.query.uid;
pool.connect((err, client, done) => {
if (err) throw err;
const fetchRow = async() =>{
await client.query('SELECT * FROM friends where follower = $1 ORDER by id ASC', [uid], (err, result) => {
done()
if(err){
console.log(err.stack)
res.status(400).json(err)
} else {
/*here I want to response rows only with JSON format, but result.rows doesn't realise that...*/
console.log(result.rows)
res.status(200).json(result.rows)
}
})
}
fetchRow()
})
})
解决方案
推荐阅读
- javascript - typescript 会在执行下一个代码之前等待循环完成吗?
- r - 如何在 R Shiny Flexdashboard 中覆盖(在单击 actionButton 时)反应性对象
- python - 导入多数组 numpy 扩展模块失败。您很可能正在尝试导入失败的 numpy 构建
- ruby - Ruby:将 curl 命令转换为 Ruby net/http 请求
- excel - 将 Excel 表格中的单元格复制到另一个 Excel 电子表格
- geoip - MaxMind 拉 Geolite2 得到 401 Unauthorized
- java - 数组java的意外结果
- mysql - mysql选择id不在
- jquery - jQuery 将 Ajax 属性大写
- c# - 使用 C# 和 ASP.NET 将数据从 Excel 文件导出到 SQL Server 表的最佳方法?