我正在尝试从一个带有Power Query的REST API获取数据。该API以200条记录为一页返回结果。每个页面将包含一个JSON结构,如下所示:
{
"start": 0,
"limit": 200,
"records": [
{
"record": {
"id": 1,
"field1": "some text",
"field2": false
}
},
{
"record": {
"id": 2,
"field1": "some text",
"field2": true
}
},
{
"record": {
"id": 3,
"field1": "some text",
"field2": false
}
}
]
}
然后,对于下一页,我为start
参数提供了一个值,该值以200为增量递增,我只需要用新页面数组的内容扩展records
数组。因此,在伪代码中,它看起来是这样的:
content ← True
i ← 1
While content
response ← get(url, http_parameters=['start' = i])
results ← results + response['records']
i ← i + response['size']
content ← size(response['records']) > 0
Endwhile
我在Python中很容易做到这一点,但我看不出M语言是如何做到这一点的,因为它没有for或while循环。我见过许多关于这个主题的问题,但每次都假设第一个响应将返回记录总数,或者它包含指向下一个页面的URL。
学习这门语言的过程相当陡峭,所以如果能给我一些建议,我将不胜感激。
发布于 2021-04-01 03:07:35
标准的出发点是根据您的需要调整Microsoft helper function。
// The getNextPage function takes a single argument and is expected to return a nullable table
Table.GenerateByPage = (getNextPage as function) as table =>
let
listOfPages = List.Generate(
() => getNextPage(null), // get the first page of data
(lastPage) => lastPage <> null, // stop when the function returns null
(lastPage) => getNextPage(lastPage) // pass the previous page to the next function call
),
// concatenate the pages together
tableOfPages = Table.FromList(listOfPages, Splitter.SplitByNothing(), {"Column1"}),
firstRow = tableOfPages{0}?
in
// if we didn't get back any pages of data, return an empty table
// otherwise set the table type based on the columns of the first page
if (firstRow = null) then
Table.FromRows({})
else
Value.ReplaceType(
Table.ExpandTableColumn(tableOfPages, "Column1", Table.ColumnNames(firstRow[Column1])),
Value.Type(firstRow[Column1])
);
发布于 2021-04-01 03:11:11
标准的出发点是根据您的需要调整Microsoft helper function。
还有some good blogs on the topic。递归/迭代让我头脑发热,直到我发现它是我们的,然后它就变得甜蜜了。
// The getNextPage function takes a single argument and is expected to return a nullable table
Table.GenerateByPage = (getNextPage as function) as table =>
let
listOfPages = List.Generate(
() => getNextPage(null), // get the first page of data
(lastPage) => lastPage <> null, // stop when the function returns null
(lastPage) => getNextPage(lastPage) // pass the previous page to the next function call
),
// concatenate the pages together
tableOfPages = Table.FromList(listOfPages, Splitter.SplitByNothing(), {"Column1"}),
firstRow = tableOfPages{0}?
in
// if we didn't get back any pages of data, return an empty table
// otherwise set the table type based on the columns of the first page
if (firstRow = null) then
Table.FromRows({})
else
Value.ReplaceType(
Table.ExpandTableColumn(tableOfPages, "Column1", Table.ColumnNames(firstRow[Column1])),
Value.Type(firstRow[Column1])
);
https://stackoverflow.com/questions/66888658
复制相似问题