简体   繁体   English

如何将 JSON 解析为 MySQL

[英]How to parse JSON to MySQL

I have a JSON string from a http request I need to store in a MySql table, columns and rows我有一个来自 http 请求的 JSON 字符串,我需要将其存储在 MySql 表、列和行中

I need to do it in Node.js.我需要在 Node.js 中做到这一点。 It's not a problem to get the JSON string via the http request.通过http请求获取JSON字符串不是问题。 http://lonobox.com/api/index.php?id=100004854 http://lonobox.com/api/index.php?id=100004854

The problem is to convert it to columns and rows and store it in MySql.问题是将其转换为列和行并将其存储在MySql中。 Alternative postgre替代 postgre

This is my JSON string这是我的 JSON 字符串

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

You can try parsing the json data using JSON.parse().您可以尝试使用 JSON.parse() 解析 json 数据。 The resultant will be an array of data.结果将是一个数据数组。 If you are open to trying other dbs then I suggest using mongodb.如果您愿意尝试其他数据库,那么我建议使用 mongodb。 In that you can directly push the data as a json.因为您可以直接将数据作为 json 推送。

You can try doing it by using body-parser and express npm modules你可以尝试使用body-parserexpress npm modules

After defining your 'app' using express and my-sql connection you can use a code similar to this example:使用 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');
  }
 });
});

This the method that I was able to find when I had to do something similar, this might or might not be the best way to approach this这是我在不得不做类似事情时能够找到的方法,这可能是也可能不是解决这个问题的最佳方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM