1

I'm trying to pull data from an API and insert it into a MySQL Database. The API has over 100 objects but I can't find any information on how to do this?

I'm using node-fetch to output the Json Data but can't loop through each object? I've added a snippet of the API.

[
  {
    "id": 1,
    "name": "Device_1"
  },
  {
    "id": 2,
    "name": "Device_2"
  }
]
Charlie Simon
  • 133
  • 12

3 Answers3

2

let responseFromApi = [ { "id": 1, "name": "Device_1" }, { "id": 2, "name": "Device_2" } ];

let insertMany = db.query( 'INSERT INTO your_table (id, name) VALUES ?', [responseFromApi.map(res => [res.id, res.name])], );

for refrence go through the documentation --> https://www.mysqltutorial.org/mysql-nodejs/insert/

You can also use query builders such as KnexJs and others

Atul Singh
  • 79
  • 5
1

If I understand what you mean, you can use foreach to access any of the features of the object, such as the example below.

   Object.keys(obj).forEach(function(k){
          console.log(k + ' - ' + obj[k].id);
     });
Ashkan
  • 43
  • 7
0

Worked it out, should have known now that I look at it, but to help anyone in the future I'll leave the solution.

const fetch = require('node-fetch');

let settings = {
    method: "Get"
};

fetch('http://127.0.0.1:3000/test', settings)
    .then(res => res.json())
    .then((json) => {
        for (var i = 0; i < json.length; i++) {
            json.id = json[i].id;
            console.log(json.id);
        }
    });
Charlie Simon
  • 133
  • 12