首页  >  问答  >  正文

Node-Express MySQL API 将 JSON 数组输出为字符串

尝试设置 Express API 服务器来获取投资组合网站的一些数据。我已经为我的“图像”列设置了带有 JSON 数据类型的 MySQL 表。 “images”应该具有画廊的多个图像链接。但是,服务器将图像数组输出为字符串而不是字符串数组。

API 服务器上的 Javascript 代码

app.get("/getWorks", (req, res) => {
  let sql = "select * from works";
  db.query(sql, (err, result) => {
    if (err) throw err;
    console.log(result);
    res.send(result);
  });
});

结果

[
  {
    "workID": 1,
    "title": "example",
    "images": "[\"https://SERVER_IP/images/example.png\", \"https://SERVER_IP/images/example.png\"]"
  }
]

解决方法

我找到了一种解决方法来获得所需的输出,添加以下内容:

result = result.map((row) => ((row.images = JSON.parse(row.images)), row));
[
  {
    "workID": 1,
    "title": "example",
    "images": ["https://SERVER_IP/images/example.png", "https://SERVER_IP/images/example.png"]
  }
]

即使我在表中将该特定列指定为 JSON 数据类型,为什么查询一开始就不输出 JSON 数组中的数据?

P粉575055974P粉575055974184 天前323

全部回复(1)我来回复

  • P粉170858678

    P粉1708586782024-03-31 11:55:58

    我解决了这个问题。我使用了错误的 MySQL 节点包。需要 MySQL2 进行 json 格式化。

    npm install mysql2
    const mysql = require("mysql2");
    

    回复
    0
  • 取消回复