简体   繁体   English

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

[英]Traverse JSON Object in Javascript with unknown key

I get a JSON String as a result from an API that looks like this:作为 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..."
            }
        }
    }
}

The goal目标
I never know what the pageid will be and I need to retrieve the extract and thumbnail .我永远不知道 pageid 是什么,我需要检索extractthumbnail The extract should be a String and the thumbnail an Object.提取应该是字符串,缩略图应该是 Object。

Wouldn't be much of an issue if it weren't for the random pageid.如果不是随机的pageid,那将不是什么大问题。

What I've tried我试过的

const thumbnail = jsonObj.query[0].thumbnail;
const extract = jsonObj.query[0].extract;

Expected result预期结果

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...";

It's a bit of a hack, but if you know there will always only be one pageid (or if you'll always want the first one), you can use Object.values :这有点小技巧,但如果你知道总是只有一个 pageid(或者如果你总是想要第一个),你可以使用Object.values

const page = Object.values(t.query.pages)[0];
console.log(page.thumbnail, page.extract);

The Object.keys function returns an array with all the keys in the given object. Object.keys function 返回一个数组,其中包含给定 object 中的所有键。 Then you may use the array that is returned to use any key of the object to access some value.然后您可以使用返回的数组来使用 object 的任何键来访问某些值。

So you can do something like this:所以你可以做这样的事情:

 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

In your specific case:在您的具体情况下:

 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);

Please note that some objects may have more than one key.请注意,某些对象可能有多个键。 In the previous example, only one key (the first one Object.keys returns) is being used.在前面的示例中,只使用了一个键(第一个Object.keys返回)。 The Object.keys function also does not guarantee any specific order in the returned array of keys. Object.keys function 也不保证返回的键数组中的任何特定顺序。

If you do not care about the key (only the value), you may use the Object.values function.如果您不关心密钥(只关心值),您可以使用Object.values function。

A combination of eg Object.values and an object destructuring assignment will do the job.例如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; }

Here is an iterative solution using object-scan这是使用对象扫描的迭代解决方案

Advantage is that it's easier to maintain (eg target a different key if the response structure changes)优点是更容易维护(例如,如果响应结构发生变化,则针对不同的键)

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

Disclaimer : I'm the author of object-scan免责声明:我是对象扫描的作者

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

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