我从 API 中得到一个 JSON 字符串,如下所示:
{
"batchcomplete": "",
"query": {
"pages": {
"682482": {
"pageid": 682482,
"ns": 0,
"title": "Human",
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Akha_cropped_hires.JPG/119px-Akha_cropped_hires.JPG",
"width": 119,
"height": 200
},
"extract": "Humans (Homo sapiens) are a species of highly intelligent primates. They are the only extant members of the subtribe Hominina and—together with chimpanzees, gorillas, and orangutans—are part of the family Hominidae (the great apes, or hominids). Humans are terrestrial animals, characterized by their erect posture and bipedal locomotion; high manual..."
}
}
}
}
目标
我永远不知道 pageid 是什么,我需要检索提取和缩略图。
摘录应该是一个字符串,缩略图应该是一个对象。
如果不是随机 pageid,就不会有太大问题。
我尝试过的
const thumbnail = jsonObj.query[0].thumbnail;
const extract = jsonObj.query[0].extract;
预期结果
thumbnail = {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Akha_cropped_hires.JPG/119px-Akha_cropped_hires.JPG",
"width": 119,
"height": 200
}
extract = "Humans (Homo sapiens) are a species of highly intelligent primates. They are the only extant members of the subtribe Hominina and—together with chimpanzees, gorillas, and orangutans—are part of the family Hominidae (the great apes, or hominids). Humans are terrestrial animals, characterized by their erect posture and bipedal locomotion; high manual...";
最佳答案
这有点像黑客,但如果你知道永远只有一个 pageid(或者如果你总是想要第一个),你可以使用 Object.values :
const page = Object.values(t.query.pages)[0];
console.log(page.thumbnail, page.extract);
关于javascript - 使用未知键遍历Javascript中的JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66081696/