javascript - 如何返回一个对象而不是数组?

标签 javascript mysql node.js express

我试图返回一个 JSON 对象,但它返回一个数组。我使用主键进行查询,因此我确信我只会得到一个结果。

这是我的方法:

router.get("/student_info/:id", (req, res, next) => {
    connection.getConnection((error, currentConnection) => {
        if (!!error) {
            console.log("Error occurred while connecting db")
        } else {
            let id = req.params.id;
            currentConnection.query("SELECT * FROM students WHERE id=" + "'" + id + "'", (error, rows, fields) => {
                if (!!error) {
                    console.log(error.message)
                } else {
                    res.status(200).json(rows);
                }
                currentConnection.release();
            });
        }
    });
});

我想要的是这样的:

    {
        "id": "171-15-8966",
        "name": "Alif Hasnain",
        "course_code": "CSE412,CSE413"
    }

但我得到的结果是这样的:

[
    {
        "id": "171-15-8966",
        "name": "Alif Hasnain",
        "course_code": "CSE412,CSE413"
    }
]

最佳答案

只需在 json 转换之前获取数组的第一个元素即可:

res.status(200).json(rows[0]);

关于javascript - 如何返回一个对象而不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60740386/

相关文章:

Javascript:检索 li 中存在的标签内容

javascript - 如何在流式传输轨道时处理 SoundCloud 的 JavaScript API 404 错误

sql - 有 Node 对象关系映射包吗?

javascript - 无法过滤嵌套的json对象

javascript - 如何将 Google 应用端点与 PhoneGap 应用集成

php - 将 "the loop"从 Wordpress 添加到任何 html/php 模板的简单方法(不是为 wordpress 制作的)

php - MySQL 查询在 PHPMyAdmin 中有效,但在 PHP 中无效

mysql - 优化关联表查询

php - mysql查询顺序错误

node.js - 已安装 Node JS NPM 模块但无法识别命令