【问题标题】:NodeJS JSON to SQL and SQL to JSON Libraries?NodeJS JSON 到 SQL 和 SQL 到 JSON 库?
【发布时间】:2017-09-26 18:31:14
【问题描述】:

所以基本上我会得到一些巨大的 JSON 文件的提要。我想将它们转换为 SQL 并将它们存储到 MySQL 数据库中。

这里的问题是,稍后我将需要从数据库中获取 SQL 文件并将它们转换为 JSON 对象。

https://sqlizer.io/#/ 类似这样的东西,它将 JSON 转换为 SQL,反之亦然。

所以我想知道是否有任何 NodeJS 模块/库具有这种功能。

谢谢。

【问题讨论】:

  • 不能将数据存储在JSON 字段中?
  • 查看stackoverflow.com/questions/33797867/…中的答案似乎SQL查询结果已经是JSON了。
  • @Wainage 将一个巨大的 JSON 对象存储到一个字段中是不是很糟糕?就像我可以将其存储为文本一样,但这很糟糕吗?
  • 一个大斑点是的。但是数据的形状是什么?它是一个数组/哈希图吗?你可以打破它。甚至添加real sql™ 字段来改进查询。

标签: mysql sql json node.js


【解决方案1】:

我看不出问题出在哪里。对于 node 中的大多数 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,这里是文档: http://knexjs.org/

【讨论】:

    猜你喜欢
    • 2015-04-22
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2011-12-23
    • 2014-02-23
    • 1970-01-01
    相关资源
    最近更新 更多