繁体   English   中英

使用未知键遍历 Javascript 中的 JSON Object

[英]Traverse JSON Object in Javascript with unknown key

作为 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 是什么,我需要检索extractthumbnail 提取应该是字符串,缩略图应该是 Object。

如果不是随机的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);

Object.keys function 返回一个数组,其中包含给定 object 中的所有键。 然后您可以使用返回的数组来使用 object 的任何键来访问某些值。

所以你可以做这样的事情:

 const partialObj = { '682482': 'Value' }; const keys = Object.keys(partialObj); console.log(keys); // Then you can access the value with the "unknown" key: console.log(partialObj[keys[0]]); //=> Value

在您的具体情况下:

 const jsonObj = { "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..." } } } }; const unknownKeys = Object.keys(jsonObj.query.pages); const unknownKey = unknownKeys[0]; // We are only using one key. const thumbnail = jsonObj.query.pages[unknownKey].thumbnail; console.log(thumbnail);

请注意,某些对象可能有多个键。 在前面的示例中,只使用了一个键(第一个Object.keys返回)。 Object.keys function 也不保证返回的键数组中的任何特定顺序。

如果您不关心密钥(只关心值),您可以使用Object.values function。

例如Object.valuesobject 解构赋值的组合将完成这项工作。

 const sample = { "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 } } } } } const { pageid, thumbnail, } = Object.values(sample.query.pages)[0]; console.log(pageid); console.log(thumbnail);
 .as-console-wrapper { min-height: 100%;important: top; 0; }

这是使用对象扫描的迭代解决方案

优点是更容易维护(例如,如果响应结构发生变化,则针对不同的键)

 // const objectScan = require('object-scan'); const myData = { batchcomplete: '', query: { pages: { 682482: { pageid: 682482, ns: 0, title: 'Human', thumbnail: { source: '...url...', width: 119, height: 200 }, extract: '...text...' } } } }; const extract = (data) => objectScan(['query.pages.*.{thumbnail,extract}'], { filterFn: ({ property, value, context }) => { context[property] = value; } })(data, {}); console.log(extract(myData)); /* => { extract: '...text...', thumbnail: { source: '...url...', width: 119, height: 200 } } */
 .as-console-wrapper {max-height: 100%;important: top: 0}
 <script src="https://bundle.run/object-scan@14.0.0"></script>

免责声明:我是对象扫描的作者

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM