当运行 Console.log(myjsonobject)
时,我在 Node.js 中有一个像这样输出的 JSON:
{
"results":
[
"id": 'xxxxxx',
"size": 'xxxxx',
"data":
[ {
"date": 'xxxxx',
"age": 'xxxx',
"grade": 'xxxxxx'
},
{
"date": 'xxxxx',
"age": 'xxxx',
"grade": 'xxxxxx'
}
.... // many more data again
]
]
"total": 'xxxxxxx',
"group": 'xxxxxxx'
}
我是 Node.js 的新手,正在努力将 myjsonobject
插入 MySQL 数据库。
最佳答案
是的,您可以在 mysql 中插入您的嵌套对象。请按照以下步骤操作:
1) 您必须创建一个包含 JSON 列 MySQL JSON Docs 的表
CREATE TABLE myjson (jdoc JSON);
2)连接mysql,我用的是mysql驱动,安装:
npm install mysql
3) 更正您的代码: 例如,在第 3 行,对象数组必须使用 [{ }] 而不是 []。
3) 正确地将数据插入您的数据库:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "youruser",
password: "yourpassword",
database: "yourdb"
});
//Your JSON nested object;
var my_json_nested_object = {
"results":
[{ // <--
"id": "xxxxxx",
"size": "xxxxx",
"data":
[ {
"date": "xxxxx",
"age": "xxxx",
"grade": "xxxxxx"
},
{
"date": "xxxxx",
"age": "xxxx",
"grade": "xxxxxx"
}
]
}], // <-- use {}
"total": "xxxxxxx",
"group": "xxxxxxx"
};
//The JSON.stringify() method converts a JavaScript value to a JSON string
var sql = "INSERT INTO myjson VALUES ('" +
JSON.stringify(my_json_nested_object) + "');";
con.query(sql, function (err, results,fields) {
if (err)
throw err;
console.log(results); //or console.log(JSON.stringify(results));
con.end();
});
关于mysql - 将嵌套的 JSON 对象插入 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48183725/