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"
  }
]

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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);
     });

Comments

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);
        }
    });

1 Comment

foreach is the recommended method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.