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.
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.
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.
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With