【问题标题】:Looping through API response Node JS循环通过 API 响应 Node JS
【发布时间】:2020-09-19 09:04:08
【问题描述】:

我正在尝试从 API 中提取数据并将其插入 MySQL 数据库。 API 有 100 多个对象,但我找不到有关如何执行此操作的任何信息?

我正在使用 node-fetch 来输出 Json 数据,但不能循环遍历每个对象?我添加了 API 的 sn-p。

[
  {
    "id": 1,
    "name": "Device_1"
  },
  {
    "id": 2,
    "name": "Device_2"
  }
]

【问题讨论】:

    标签: node.js node-fetch


    【解决方案1】:

    让 responseFromApi = [ { “身份证”:1, “名称”:“设备_1” }, { “身份证”:2, “名称”:“设备_2” } ];

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

    参考文档 --> https://www.mysqltutorial.org/mysql-nodejs/insert/

    您还可以使用 KnexJs 等查询构建器

    【讨论】:

      【解决方案2】:

      如果我理解您的意思,您可以使用foreach 访问对象的任何功能,如下例所示。

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

      【讨论】:

        【解决方案3】:

        解决了,现在我看应该知道,但为了帮助将来的任何人,我会留下解决方案。

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

        【讨论】:

        • foreach 是推荐的方法。
        猜你喜欢
        • 1970-01-01
        • 2013-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多