Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a nested JSON Object into MySQL

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.

like image 596
Pmicezjk Avatar asked Jan 10 '18 09:01

Pmicezjk


People also ask

Can we store JSON object in MySQL?

MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents. The JSON data type provides these advantages over storing JSON-format strings in a string column: Automatic validation of JSON documents stored in JSON columns.

Can JSON objects be nested?

Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.

Can we store JSON array in MySQL?

Note that any database will accept JSON documents as a single string blob. However, MySQL and PostgreSQL support validated JSON data in real key/value pairs rather than a basic string.


1 Answers

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();
});
like image 198
Leonardo Avatar answered Nov 15 '22 06:11

Leonardo