javascript - 如何从这些 JSON 对象中过滤掉值

标签 javascript node.js json

我正在使用返回给我 JSON 代码的在线 API,但我不知道如何过滤掉 JSON 代码中的“名称”值。我尝试过滤的 JSON 在许多对象中,我尝试了许多不同的方法。如何从每个对象中获取“名称”的值?我试过 .people.name 但我总是得到一个空白输出或者它只会说“[object Object][object Object][object Object][object Object][object Object]”

JSON 响应:

{
  "message": "success",
  "number": 6,
  "people": [
    {
      "craft": "ISS",
      "name": "Oleg Kononenko"
    },
    {
      "craft": "ISS",
      "name": "David Saint-Jacques"
    },
    {
      "craft": "ISS",
      "name": "Anne McClain"
    },
    {
      "craft": "ISS",
      "name": "Alexey Ovchinin"
    },
    {
      "craft": "ISS",
      "name": "Nick Hague"
    },
    {
      "craft": "ISS",
      "name": "Christina Koch"
    }
  ]
}

我在 NodeJS 中的代码:

request('http://api.open-notify.org/astros.json', (error, response, html) => {

        if (!error && response.statusCode == 200)
        {
            let astroJSON = JSON.parse(html);

            let astroNum = astroJSON.number;
            let astroNames = JSON.stringify(astroJSON.people); // This is what I need help with!
            console.log("Number: " + astroNum);
            console.log("Crew names: " + astroNames); // Return the JSON response that I sent above. 
        }
    });

最佳答案

尝试使用 Array#prototype#map

const data = `{
  "message": "success",
  "number": 6,
  "people": [
    {
      "craft": "ISS",
      "name": "Oleg Kononenko"
    },
    {
      "craft": "ISS",
      "name": "David Saint-Jacques"
    },
    {
      "craft": "ISS",
      "name": "Anne McClain"
    },
    {
      "craft": "ISS",
      "name": "Alexey Ovchinin"
    },
    {
      "craft": "ISS",
      "name": "Nick Hague"
    },
    {
      "craft": "ISS",
      "name": "Christina Koch"
    }
  ]
}`;

const obj = JSON.parse(data);

const astroNames = obj.number;

// Join the crew names with a comma
const crew = obj.people.map(x => x.name).join(', ');
console.log(crew);

将您的代码更改为:

request('http://api.open-notify.org/astros.json', (error, response, html) => {

        if (!error && response.statusCode == 200)
        {
            let astroJSON = JSON.parse(html);

            let astroNum = astroJSON.number;
            let astroNames = astroJSON.people.map(x => x.name).join(', ');
            console.log("Number: " + astroNum);
            console.log("Crew names: " + astroNames); // Return the JSON response that I sent above. 
        }
    });

关于javascript - 如何从这些 JSON 对象中过滤掉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56740194/

相关文章:

javascript - 使用 es6 模块创建自定义 "event listener"

node.js - Node JS 与 SSL pfx 文件的问题

node.js - 部署heroku应用程序失败

java - 如何获取 Hibernate 对象并将其映射到 JSON

javascript - 如何在另一个 JavaScript 文件中包含一个 JavaScript 文件?

字符串中包含 '/' 的 JavaScript 正则表达式

javascript - 当 return new Promise((resolve, reject) => {}) 忘记调用 resolve 或 reject 时会发生什么?

java - 从 JSON 反序列化时可以限制可能的值吗?

java - 为日志格式化 protobuf

javascript - 使用 React Native 的 HTML5 Canvas