mysql - 如何从 Nodejs Mysql 获取 JSON 类型作为 JSON 而不是 String

标签 mysql node.js mysql-5.7

我在 MySQL 5.7 中有 TEST(id INT, attribute JSON) 表

当我尝试使用 mysql 包在 Nodejs 中查询表时,如下所示

con.query("select * from TEST where id=?", [req.params.id], function (err, results) {
    if (err) throw err;
    console.log(results);
  });

我得到以下输出

[
   {
        "id": 2,
        "package": "{\"tag\": \"tag1\", \"item\": \"item1\"}"
    }
]

有没有办法在不迭代数组的情况下将上述结果中的包项作为 JSON 对象而不是字符串,然后执行 JSON.parse 将字符串转换为 JSON?

预期输出

[
       {
            "id": 2,
            "package": {"tag": "tag1", 
                        "item": "item1"}
        }
    ]

最佳答案

Is there a way to get the package item in the above result as JSON object instead of a string without iterating the array and do JSON.parse to convert string to JSON?

MySQL 5.7 支持 JSON data type ,因此您可以将包类型更改为 JSON,并且如果您的客户端支持此数据类型,则不必在每一行上迭代和执行 JSON.parse

请记住 mysql包不支持它,但是mysql2

CREATE TABLE `your-table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `package` json DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

现在包将是一个数组/对象:

con.query("select * from TEST where id=?", [req.params.id], function (err, results) {
    if (err) throw err;
    console.log(results[0].package.tag); // tag1 using mysql2
    console.log(results[0].package.item); // item1 using mysql2
});

如果你运行的 MySQL 版本低于 5.7 或者你不想使用 JSON 类型,你将需要自己迭代和解析它。

你可以使用这个衬垫:

results = results.map(row => (row.package = JSON.parse(row.package), row));

如果您想知道是否应该将 JSON 存储在关系数据库中,可以在这个问题中进行很好的讨论:

Storing JSON in database vs. having a new column for each key

关于mysql - 如何从 Nodejs Mysql 获取 JSON 类型作为 JSON 而不是 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49869139/

相关文章:

mysql - 选择 account_id 并从另一个表中获取名称

php - 使用 Union All 添加按日期顺序回显 SQL 数据

node.js - 如何在 Nodejs 中设置谷歌日历网络钩子(Hook)?

node.js - 更新 Jest 测试库后出现意外标记 (SyntaxError)

mysql - 在只读事务中创建临时表 - MYSQL 5.7

java - 将 MySql 与 Servlet 连接用于登录页面

php - MySQL - 存储坐标以避免重复

mysql - 在一列中找出时间范围

node.js - 从虚拟文件系统加载 Node 模块

mysql - mysql.user 表中的 max_connections 列有什么用?