從這個 API ( https://api.dicionario-aberto.net/random ) 中獲取一個單詞給了我整個物件:
{
"word": "linguaraz",
"wid": 74891,
"sense": 1
}
我怎樣才能只回傳這個物件中的單詞值?
這是我的代碼:
const getWord = async function () {
const response = await fetch ("https://api.dicionario-aberto.net/random?get.value")
const words = await response.text();
const wordArray = words.split("\n");
const randomIndex = Math.floor(Math.random() * wordArray.length);
word = wordArray[randomIndex].trim();
placeholder(word);
};
uj5u.com熱心網友回復:
您需要先將您的 api 結果轉換為 JSON 而不是文本,然后訪問 word 會更容易,像這樣
async function getData(){
res = await fetch('https://api.dicionario-aberto.net/random');
data = await res.json();
console.log(data.word);
}
getData();
uj5u.com熱心網友回復:
將獲取資料轉換為 json 并將其作為物件屬性讀取:
const getWord = async function () {
const response = await fetch ("https://api.dicionario-aberto.net/random?get.value")
const words = await response.json();
placeholder(word);
};
uj5u.com熱心網友回復:
使用以下方法轉換為 JSON:
const obj = JSON.parse(await response)
或者
const obj = await response.json()
通過輸入鍵獲取值:
obj.<key_name>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/486010.html
標籤:javascript
