javascript - 使用未知键遍历Javascript中的JSON对象

标签 javascript object

我从 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/

相关文章:

javascript - 如何防止 Javascript 中带有子菜单的响应式下拉子菜单中的默认行为

java - 在类中定义数组时出错

javascript - javascript中的深浅合并

java - 如何创建一个只有一个变量的对象,该变量可以是两种数据类型之一?

javascript - 如何像触摸光标一样查看图像?

javascript - 模块版本不匹配

javascript - JavaScript 的最长执行时间

javascript - 确认框 Twig、Symfony 和 Javascript

javascript - 使用相似的名称动态访问表单值

java - 如何正确地按降序对对象数组进行排序并在 Java 中搜索它们?