MS Power Query循环

时间:2016-03-01 18:22:16

标签: json loops powerquery

这是来自https://privacy.google.com/的不同循环问题。

我使用Power Query从api.automatic.com提取数据;具体来说,一个旅行清单。我能够提取第一组信息,但我无法弄清楚如何循环获取所有信息。

这是我到目前为止所做的:

print(var)

输出的JSON返回let Source = Web.Contents("https://api.automatic.com/trip/",[Headers=[#"Authorization"="Bearer XXX"]]), #"Imported JSON" = Json.Document(Source), results = #"Imported JSON"[results], #"Converted to Table" = Table.FromList(results, Splitter.SplitByNothing(), null, null, ExtraValues.Error), #"Expanded Column1" = Table.ExpandRecordColumn(#"Converted to Table", "Column1", {"url", "id", "driver", "user", "started_at", "ended_at", "distance_m", "duration_s", "vehicle", "start_location", "start_address", "end_location", "end_address", "path", "fuel_cost_usd", "fuel_volume_l", "average_kmpl", "average_from_epa_kmpl", "score_events", "score_speeding", "hard_brakes", "hard_accels", "duration_over_70_s", "duration_over_75_s", "duration_over_80_s", "vehicle_events", "start_timezone", "end_timezone", "city_fraction", "highway_fraction", "night_driving_fraction", "idling_time_s", "tags"}, {"url", "id", "driver", "user", "started_at", "ended_at", "distance_m", "duration_s", "vehicle", "start_location", "start_address", "end_location", "end_address", "path", "fuel_cost_usd", "fuel_volume_l", "average_kmpl", "average_from_epa_kmpl", "score_events", "score_speeding", "hard_brakes", "hard_accels", "duration_over_70_s", "duration_over_75_s", "duration_over_80_s", "vehicle_events", "start_timezone", "end_timezone", "city_fraction", "highway_fraction", "night_driving_fraction", "idling_time_s", "tags"}) in #"Expanded Column1" 下的值,该值是获取 next 数据集的URL。如何让PQ获取该值,使用该URL重新生成,并继续这样做,直到_metadata.next值为空或空白?

1 个答案:

答案 0 :(得分:0)

使用List.Generate提取数据,直到下一个标记为空。

  

List.Generate(初始为函数,条件为函数,下一个为函数,可选选择器为可为空的函数)作为列表

带说明的代码(未经我的访问,请经过测试):

let
    // Helper function to get results and next token.
    get = (url as any, headers as any) as record =>
        let
            source = Json.Document(Web.Contents(url, headers)),
            results = try source[results] otherwise null,
            next = try source[_metadata][next] otherwise null,
            return = [results=results, next=next]
        in
            return,

    url = "https://api.automatic.com/trip/",
    headers = [Headers=[#"Authorization"="Bearer XXX"]],

    // Returns a list of lists of records.
    return = 
        List.Generate(
            // Initial value.
            ()=> get(url, headers),
            // If condition is true select (make a list) the result.
            each [results] <> null,
            // Generate the next list if condition is true.
            each get([next], headers),
            // Return (select) only [results].
            each [results])
in
    return

了解each关键字有什么帮助:

  

每个关键字用于轻松创建简单功能。 “每个...”是带有参数“()=> ...”的函数签名的语法糖。

     

与查找操作符结合使用时,每个方法都非常有用,默认情况下将其应用到each [CustomerID]each _[CustomerID]相同,与(_) => _[CustomerID]