首页 > 解决方案 > 无法过滤类似 JSON 的东西

问题描述

我正在使用来自https://swapi.co/的数据在 node.js 中编写一个应用程序。我的一项功能需要检查我的数据库中是否存在指定的行星,如果不存在,api 应该从 swapi 下载行星的数据,但不知何故我无法检索有关按名称指定的行星的数据,我只能获取格式提供的数据这个链接:https://swapi.co/api/planets/?format=json

方法代码:

router.route('/Planets')
    .post(function (req, res) {
        var planet = new Planet(req.body);
        //validate planet.name here
        Planet.find({name: planet.name}, function (err, planet) {
            if (err) {
                res.status(500).send(err);
            }
            if (planet == '') {
                console.log("action: planet not found");
                request.get(
                    'https://swapi.co/api/planets/?format=json',
                    {json: true},
                    function (error, response, body) {
                        console.log(body);
                    }
                );
                // planet.save();
                res.status(201).send(planet);
            } else {
                res.status(201).send(planet);
            }
        })
    })
    .get(function (req, res) {
        Planet.find(function (err, planets) {
            if (err) {
                res.status(500).send(err);
            } else {
                res.json(planets);
            }
        });
    });

标签: javascriptjsonnode.jsfilteringresponse

解决方案


这是 JSON。行星存储在results. 所以结果是对象数组,现在您可以使用foror遍历数组的所有元素in

您可以随意操作、循环、过滤器等。

fetch("https://swapi.co/api/planets/?format=json")
  .then(res => res.json())
  .then(res => {
    console.log(res);
    // Array of planets stored in res.results
    for (let i=0; i<res.results.length; i++) {
      console.log("Name:", res.results[i].name, "Data:", res.results[i])
    }
  });


推荐阅读