Power Query如何根据传入参数动态返回对应字段?
Power Query M语言动态访问Record字段解决方案
你的问题核心是M语言中直接用Source[字段名]的写法只能识别字面量,无法通过变量动态指定字段。解决这个问题要用Record.Field函数,它支持传入字段名字符串参数来动态取值。
修改后的代码如下:
(URLPath as text, Page as number) => let Source = Json.Document(Web.Contents("https://XX.com/api/v2/" & URLPath , [Query =[per_page="100",page=Number.ToText(Page)],Timeout=#duration(0, 0, 1, 0)])), DynamicResult = Record.Field(Source, URLPath) in DynamicResult
关键说明
Record.Field(记录对象, 字段名字符串)是M语言中动态访问Record字段的标准方法,第一个参数是要操作的Record,第二个参数是存储字段名的变量或字符串。- 如果需要处理字段不存在的情况,可以额外搭配
Record.HasFields做判断,避免报错:
(URLPath as text, Page as number) => let Source = Json.Document(Web.Contents("https://XX.com/api/v2/" & URLPath , [Query =[per_page="100",page=Number.ToText(Page)],Timeout=#duration(0, 0, 1, 0)])), DynamicResult = if Record.HasFields(Source, URLPath) then Record.Field(Source, URLPath) else null in DynamicResult
内容的提问来源于stack exchange,提问作者work monitored
相关产品推荐
相关产品推荐

