7

I have a JSON that outputs like this in Node.js when running 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'
}

I'm new to Node.js and struggling to insert myjsonobject in MySQL database.

1
  • You would create 2 or 3 tables with relations to each other, then insert the data accordingly. Your question is much too broad to be answered here Commented Jan 10, 2018 at 9:48

1 Answer 1

5

Yes, you can insert your nested object in mysql. Follow these steps:

1) You must create an table that contains a JSON column, MySQL JSON Docs

CREATE TABLE myjson (jdoc JSON);

2) Connect to mysql, I'm using the mysql driver, install it:

npm install mysql

3) Correct your code: For example,at line 3, an object array must use [{ }] and not [].

3) Properly insert data to your database:

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();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.