0
所以基本上我會得到幾個巨大的JSON文件的飼料。我想將它們轉換爲SQL並將它們存儲到MySQL數據庫中。NodeJS JSON到SQL和SQL到JSON庫?
這裏的問題是,稍後我將需要從數據庫中獲取SQL文件並將它們轉換爲JSON對象。
https://sqlizer.io/#/就像這樣,它將JSON轉換爲SQL,反之亦然。
所以我想知道是否有任何NodeJS模塊/庫具有這種類型的功能。
謝謝。
所以基本上我會得到幾個巨大的JSON文件的飼料。我想將它們轉換爲SQL並將它們存儲到MySQL數據庫中。NodeJS JSON到SQL和SQL到JSON庫?
這裏的問題是,稍後我將需要從數據庫中獲取SQL文件並將它們轉換爲JSON對象。
https://sqlizer.io/#/就像這樣,它將JSON轉換爲SQL,反之亦然。
所以我想知道是否有任何NodeJS模塊/庫具有這種類型的功能。
謝謝。
我看不出問題在哪裏。在節點中大多數的sql庫中,當在sql中進行查詢時,你會得到json或者至少你得到的數據可以用JSON.stringify
轉換成JSON。
讓我們說,我們與knex和Postgres這樣做:
const db = require('knex')({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test'
}
});
/*
Let assume the content of the json files is this way:
[
{
"name": "foo",
"last_name": "bar"
},
{
"name": "foo",
"last_name": "bar"
}
];
Schema of table should be (
name TEXT NOT NULL,
last_name TEXT NOT NULL
)
*/
// these are the files
const myFilesToRead = ['./file1.json', './file2.json'];
// we are looping through myFilesToRead
// reading the files
// running queries for each object
Promise.all(
myFilesToRead.map((file) => {
// yes you can require json files :)
const fContent = require(file);
return Promise.all(fContent.map((obj) => {
// knex is a query builder, it will convert the code below to an SQL statement
return db('table_name')
.insert(obj)
.returning('*')
.then((result) => {
console.log('inserted', result);
return result;
});
}));
})
)
.then((result) => {
// let's now get these objects back
return db('table_name')
.select('*');
})
.then((result) => {
// that's it
console.log(JSON.stringify(result));
});
如果你想了解knex,這裏是DOC: http://knexjs.org/
在'''JSON'存儲數據''字段不是一個選項? – Wainage
請參閱https://stackoverflow.com/questions/33797867/convert-sql-object-to-valid-json-string-in-node-js-azure中的答案,似乎SQL查詢結果已經是JSON。 –
@Wainage將巨大的JSON對象存儲到一個字段是不好的?就像我可以將它作爲文本存儲,但是那樣不好? – TheMainJoy