如何访问值为未知整数的JS对象属性?

时间:2022-05-01 23:05:18

The JSON response returned from this wikipedia API call is a series of nested objects. To travel down the object property chain and access the text of interest, I have to first access a property whose value is a random number, dependent upon the wikipedia page I query by title.

这个wikipedia API调用返回的JSON响应是一系列嵌套对象。要沿着对象属性链移动并访问感兴趣的文本,我必须首先访问一个值为随机数的属性,这取决于wikipedia页面I按标题进行查询。

An example for the page titled "San%20Francisco" (page id = 49728):

标题为“San%20Francisco”的页面示例(页面id = 49728):

Object Property Chain:

对象属性链:

responseJSON.wiki[0].query.pages[<<page id>>].extract

Example API Call: https://en.wikipedia.org/w/api.php/?origin=*&format=json&action=query&prop=extracts&exintro=&explaintext=&titles=San%20Francisco

示例API调用:https://en.wikipedia.org/w/api.php/?origin= *格式= json&action = query&prop = extracts&exintro = &explaintext =标题=圣% 20

Is there some way that I can identify the property whose value is a random integer? There is only one child of pages in the chain whose value is an integer. I cannot think of another solution and do not know of any JSON parsing method that would be effective.

是否有某种方法可以识别值为随机整数的属性?链中只有一个子页的值是整数。我想不出其他解决方案,也不知道有哪种JSON解析方法是有效的。

I am inexperienced with AJAX requests and am making my ajax call in this way using jQuery. I would like to mention this in case I am doing something naive:

我对AJAX请求没有经验,并且正在使用jQuery进行AJAX调用。我想提一下,以防我做了一些幼稚的事情:

var getWiki = function (obj) {
    return $.ajax({
        url: "http://en.wikipedia.org/w/api.php" +
            "?origin=*" + "&format=json" +
            "&action=query" + "&prop=extracts" +
            "&exintro=" + "&explaintext=" + "&titles=" +
            obj.position,
        method: 'GET'
    });
};

3 个解决方案

#1


1  

Well, if there is always a single property on pages object then you can try either method:

如果pages对象中总是有一个属性,那么你可以尝试以下两种方法:

if (typeof Object.values !== 'function') {
  Object.values = obj => Object.keys(obj).map(key => obj[key]);
}

const responseJSON = {
  "batchcomplete": "",
  "query": {
    "pages": {
      "49728": {
        "pageid": 49728,
        "ns": 0,
        "title": "San Francisco",
        "extract": "Some text"
      }
    }
  }
}

const pages = responseJSON.query.pages;

const extractedWithKeys = pages[Object.keys(pages)[0]];
const extractedObjValues = Object.values(pages)[0];

console.log(extractedWithKeys, extractedObjValues)

#2


1  

If your object has only a single key, you can get it using Object.keys(object)[0] and then perform a dynamic bracket-notation property access on the original object. (This is what the dig utility does in the example below.)

如果对象只有一个键,可以使用object. keys(object)[0]获取它,然后对原始对象执行动态的brackey -notation属性访问。(这就是挖掘工具在下面的例子中做的事情。)

Also note that you can use .promise() to make handling your JSON response a bit tidier. I would suggest you add type: 'json' to your AJAX request, too, so that you don't have to parse the string data yourself.

还要注意,您可以使用.promise()使处理JSON响应更加整洁。我建议您也向AJAX请求添加type: 'json',这样您就不必自己解析字符串数据了。

function getWiki(obj) {
  return $.ajax({
    url: "http://en.wikipedia.org/w/api.php" +
      "?origin=*" + "&format=json" +
      "&action=query" + "&prop=extracts" +
      "&exintro=" + "&explaintext=" + "&titles=" +
      obj.position,
    method: 'GET',
    type: 'json'
  }).promise()
}


function dig(object) {
  return object[Object.keys(object)[0]]
}


getWiki({
    position: 'San Francisco'
  })
  .then(function(json) {
    console.log(
      dig(json.query.pages).extract //=> 'San Francisco (SF) ...'
    )
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

#3


0  

You can actually do this without Object.keys or other similar tricks if you add the indexpageids parameter to the query.

实际上你可以不用对象来做这个。如果将indexpageids参数添加到查询中,则使用键或其他类似的技巧。

Example API call: https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&indexpageids=1&titles=San+Francisco&exintro=1&explaintext=1

示例API调用:https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&indexpageids=1&titles=San + Francisco&exintro = 1 &explaintext = 1

Example JSON output:

示例JSON输出:

{
    "batchcomplete": "",
    "query": {
        "pageids": [
            "49728"
        ],
        "pages": {
            "49728": {
                "pageid": 49728,
                "ns": 0,
                "title": "San Francisco",
                "extract": "San Francisco (initials SF) <snip>"
            }
        }
    }
}

Then you can use something like data.query.pages[data.query.pageids[0]].extract to get the extract (although bear in mind that sometimes no pages may be returned, depending on what query you use).

然后可以使用data.query.pages[data.query.pageids[0]]之类的东西。提取以获取提取(尽管要记住,有时可能不会返回任何页面,这取决于您使用的查询)。

Wikipedia's API sandbox is useful for discovering parameters like indexpageids - experimenting there is usually quicker than reading the docs.

*的API沙箱对于发现indexpageids这样的参数很有用——在那里进行实验通常比阅读文档要快。

#1


1  

Well, if there is always a single property on pages object then you can try either method:

如果pages对象中总是有一个属性,那么你可以尝试以下两种方法:

if (typeof Object.values !== 'function') {
  Object.values = obj => Object.keys(obj).map(key => obj[key]);
}

const responseJSON = {
  "batchcomplete": "",
  "query": {
    "pages": {
      "49728": {
        "pageid": 49728,
        "ns": 0,
        "title": "San Francisco",
        "extract": "Some text"
      }
    }
  }
}

const pages = responseJSON.query.pages;

const extractedWithKeys = pages[Object.keys(pages)[0]];
const extractedObjValues = Object.values(pages)[0];

console.log(extractedWithKeys, extractedObjValues)

#2


1  

If your object has only a single key, you can get it using Object.keys(object)[0] and then perform a dynamic bracket-notation property access on the original object. (This is what the dig utility does in the example below.)

如果对象只有一个键,可以使用object. keys(object)[0]获取它,然后对原始对象执行动态的brackey -notation属性访问。(这就是挖掘工具在下面的例子中做的事情。)

Also note that you can use .promise() to make handling your JSON response a bit tidier. I would suggest you add type: 'json' to your AJAX request, too, so that you don't have to parse the string data yourself.

还要注意,您可以使用.promise()使处理JSON响应更加整洁。我建议您也向AJAX请求添加type: 'json',这样您就不必自己解析字符串数据了。

function getWiki(obj) {
  return $.ajax({
    url: "http://en.wikipedia.org/w/api.php" +
      "?origin=*" + "&format=json" +
      "&action=query" + "&prop=extracts" +
      "&exintro=" + "&explaintext=" + "&titles=" +
      obj.position,
    method: 'GET',
    type: 'json'
  }).promise()
}


function dig(object) {
  return object[Object.keys(object)[0]]
}


getWiki({
    position: 'San Francisco'
  })
  .then(function(json) {
    console.log(
      dig(json.query.pages).extract //=> 'San Francisco (SF) ...'
    )
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

#3


0  

You can actually do this without Object.keys or other similar tricks if you add the indexpageids parameter to the query.

实际上你可以不用对象来做这个。如果将indexpageids参数添加到查询中,则使用键或其他类似的技巧。

Example API call: https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&indexpageids=1&titles=San+Francisco&exintro=1&explaintext=1

示例API调用:https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&indexpageids=1&titles=San + Francisco&exintro = 1 &explaintext = 1

Example JSON output:

示例JSON输出:

{
    "batchcomplete": "",
    "query": {
        "pageids": [
            "49728"
        ],
        "pages": {
            "49728": {
                "pageid": 49728,
                "ns": 0,
                "title": "San Francisco",
                "extract": "San Francisco (initials SF) <snip>"
            }
        }
    }
}

Then you can use something like data.query.pages[data.query.pageids[0]].extract to get the extract (although bear in mind that sometimes no pages may be returned, depending on what query you use).

然后可以使用data.query.pages[data.query.pageids[0]]之类的东西。提取以获取提取(尽管要记住,有时可能不会返回任何页面,这取决于您使用的查询)。

Wikipedia's API sandbox is useful for discovering parameters like indexpageids - experimenting there is usually quicker than reading the docs.

*的API沙箱对于发现indexpageids这样的参数很有用——在那里进行实验通常比阅读文档要快。