gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:55:12 25 4
gpt4 key购买 nike

我正在使用返回给我 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com