I have a JSON string from a http request I need to store in a MySql table, columns and rows
I need to do it in Node.js. It's not a problem to get the JSON string via the http request. http://lonobox.com/api/index.php?id=100004854
The problem is to convert it to columns and rows and store it in MySql. Alternative postgre
This is my JSON string
[
{
"200004854": {
"temperature": "14.2",
"humidity":"68"
}
},
{
"200005584": {
"temperature": "20",
"humidity":"51"
}
},
{
"100004854": {
"barometer":"1002"
}
}
]
You can try parsing the json data using JSON.parse(). The resultant will be an array of data. If you are open to trying other dbs then I suggest using mongodb. In that you can directly push the data as a json.
You can try doing it by using body-parser and express npm modules
After defining your 'app' using express and my-sql connection you can use a code similar to this example:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.