将嵌套的JSON对象插入MySQL

Pmi*_*zjk 5 mysql json node.js

我有一个运行时在Node.js中输出如下的JSON Console.log(myjsonobject):

{
"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'
}
Run Code Online (Sandbox Code Playgroud)

我是Node.js的新手并且很难myjsonobject在MySQL数据库中插入.

Leo*_*rdo 5

是的,您可以在 mysql 中插入嵌套对象。按着这些次序:

1)您必须创建一个包含 JSON 列的表,MySQL JSON Docs

CREATE TABLE myjson (jdoc JSON);
Run Code Online (Sandbox Code Playgroud)

2)连接mysql,我使用的是mysql驱动,安装它:

npm install mysql
Run Code Online (Sandbox Code Playgroud)

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();
});
Run Code Online (Sandbox Code Playgroud)