【问题标题】:How to parse JSON to MySQL如何将 JSON 解析为 MySQL
【发布时间】:2019-09-15 18:32:28
【问题描述】:

我有一个来自 http 请求的 JSON 字符串,我需要将其存储在 MySql 表、列和行中

我需要在 Node.js 中完成。通过 http 请求获取 JSON 字符串是没有问题的。 http://lonobox.com/api/index.php?id=100004854

问题是将其转换为列和行并存储在MySql中。替代postgre

这是我的 JSON 字符串

[
    {
        "200004854": {
            "temperature": "14.2",
            "humidity":"68"
        }
    },
    {
        "200005584": {
            "temperature": "20",
            "humidity":"51"
        }
    },
    {
        "100004854": {
            "barometer":"1002"
        }
    }
]

【问题讨论】:

    标签: mysql node.js json http


    【解决方案1】:

    您可以尝试使用 JSON.parse() 解析 json 数据。 结果将是一个数据数组。 如果您愿意尝试其他数据库,那么我建议使用 mongodb。 你可以直接将数据作为 json 推送。

    【讨论】:

      【解决方案2】:

      您可以尝试使用body-parser 和express npm 模块来实现

      使用 express 和 my-sql 连接定义您的“应用程序”后,您可以使用类似于此示例的代码:

      app.use(bodyParser.json())
      
      app.get('/', function(req, res) {                        //handles request when URL is accessed
        res.sendFile(path.join(__dirname+ '/myfile.html'));
      });
      
      app.post('/', function(req, res) {                       //handles request when data is sent
      
      var jsondata = req.body;
      var values = [];
      
      for(var i=0; i< jsondata.length; i++)
        values.push([jsondata[i].name,jsondata[i].age]);
      
      connection.query('INSERT INTO members (name, age) VALUES ?', [values], function(err,result) {
        if(err) {
           res.send('Error encountered');
        }
       else {
           res.send('Data sent successfully');
        }
       });
      });
      
      

      当我不得不做类似的事情时,我能够找到这种方法,这可能是也可能不是解决这个问题的最佳方法

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-25
        • 1970-01-01
        • 1970-01-01
        • 2023-04-10
        • 2018-07-23
        • 1970-01-01
        • 2017-09-08
        • 1970-01-01
        相关资源
        最近更新 更多