我在 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
。
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/