美好的一天,我正在嘗試使用api獲取某些值,我能做的最大值是輸出所有的json
const api_url = 'https://api.battlemetrics.com/servers/3753675'
async function getData() {
const response = await fetch(api_url);
const json = await response.json();
const { data } = json;
console.log(data)
}
getData();
請告訴我如何獲取元素,我試過這樣:
const api_url = 'https://api.battlemetrics.com/servers/3753675'
async function getData() {
const response = await fetch(api_url);
const json = await response.json();
const { name, id, status } = json;
console.log(name, id, status)
}
getData();
但我得到“未定義未定義未定義”
我要求的物件:
{"data":{"type":"server","id":"3753675","attributes":{"id":"3753675","name":"Rusticated.com Sandbox - Creative | Minigames | Bedwars\r","address":null,"ip":"199.231.233.240","port":28015,"players":201,"maxPlayers":1000,"rank":1,"location":[-87.618889,41.875744],"status":"online","details":{"official":false,"rust_type":"modded","map":"BuildBattleArenaScrimGames","environment":"w","rust_ent_cnt_i":0,"rust_fps":43680,"rust_fps_avg":43680,"rust_gc_cl":null,"rust_gc_mb":null,"rust_hash":"","rust_headerimage":"https://cdn.discordapp.com/attachments/811789078105554984/832668733184671754/Rusticated_Mini_Games_Banner_512x256.png","rust_mem_pv":null,"rust_mem_ws":null,"pve":false,"rust_uptime":null,"rust_url":"https://rustminigames.com","rust_world_seed":1337,"rust_world_size":null,"rust_description":"Rusticated Minigames Beta \n Bedwars \n Creative \n GunGame \n Targets \n More Coming Soon...","rust_modded":true,"rust_queued_players":0,"rust_born":"2022-06-05T00:00:00.000Z","rust_last_ent_drop":"2021-08-06T00:10:18.261Z","rust_last_seed_change":"2020-09-03T18:33:52.047Z","rust_last_wipe":"2021-08-06T00:10:18.261Z","rust_last_wipe_ent":29035,"serverSteamId":"90159726978107400"},"private":false,"createdAt":"2019-06-18T18:35:26.890Z","updatedAt":"2022-06-06T10:05:57.516Z","portQuery":28038,"country":"US","queryStatus":"valid"},"relationships":{"game":{"data":{"type":"game","id":"rust"}}}},"included":[]}
uj5u.com熱心網友回復:
如果你想得到你說的物件,試試這個。
const API_URL = 'https://api.battlemetrics.com/servers/3753675';
async function getData() {
const response = await fetch(API_URL);
const json = await response.json();
console.log(json); // you need to check json first. (*)
}
getData();
然后你可以使用解構。
const API_URL = 'https://api.battlemetrics.com/servers/3753675';
async function getData() {
const response = await fetch(API_URL);
const json = await response.json();
const { name, id, status } = json.data.attributes; // (*)
console.log(name, id, status);
}
getData();
uj5u.com熱心網友回復:
您只需要將:替換
const { name, id, status } = json;
為:
const {
data: {
id,
attributes: { name, status }
}
} = json;
因為您的鍵不是直接進入回應,而是嵌套的。
uj5u.com熱心網友回復:
您可以訪問這樣的值:
const id = json.data.attributes.id;
const name = json.data.attributes.name;
const status = json.data.attributes.status;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/486541.html
標籤:javascript json
