在 Azure 数据工厂中读取变量 JSON 的问题

Issue reading a variable JSON in Azure Data Factory

我的管道收到 JSON 文件的路径和名称。

这是我创建的流程的一部分:

查找步骤用于读取 JSON 文件,稍后我需要在设置变量步骤中使用此公式获取非常具体的值:

@{activity('Lookup1').output.firstRow.Information.Area.AreaName}

这是文件的一部分的小示例:

{
  .....
  "Information": {
    "Area": {
      "AreaName": "General",
      "Workers":[
       ......
       ]
   }
}

但有时,我只能得到这个:

{
  .....
  "Information": null
}

对于第一个示例,我没有任何问题,但是对于第二个示例,我遇到了麻烦,因为该值不存在。我的问题是,如果我需要的信息不存在,如何避免错误?类似于 sql 服务器中的松散模式。

有一个黑客...

设置变量时尽量使用if

这是一个通过三个步骤创建的管道,以展示其工作原理:

1.查找: 像您一样阅读 json。

2。 FirstRow: 用第一行的内容设置一个变量。

@{activity('Lookup1').output.firstRow}

3。 Area: 测试变量是否包含“AreaName”并且仅当 TRUE 时才将 AreaName 分配给变量。

if(contains(variables('FirstRow'), 'Area'),activity('Lookup1').output.firstRow.Information.Area.AreaName, null)

参考: https://endjin.com/blog/2021/02/how-to-safely-reference-a-nullable-activity-output-in-synapse-pipelines-and-azure-data-factory

您可以使用类似的逻辑在单个步骤中使用,在动态值中设置为以下值。

@if(equals(activity('Lookup1').output.firstRow.Information,null),'null',activity('Lookup1').output.firstRow.Information.Area.AreaName)

这里有一个更简洁的方法:

@coalesce(activity('Lookup1').output?.firstRow?.Information, 'null')

Docs coalesce:计算表达式列表和 returns 第一个 non-null(或 non-empty 字符串)表达式。

并把 ? (safe-null 操作符) returns null 如果点符号中没有 firstRowInformation,检查 docs.

还有比较复杂的查询,docs:

The below example shows a complex example that references a deep sub-field of activity output. To reference a pipeline parameter that evaluates to a sub-field, use [] syntax instead of dot(.) operator (as in case of subfield1 and subfield2), as part of an activity output.

@activity('*activityName*').output.*subfield1*.*subfield2*[pipeline().parameters.*subfield3*].*subfield4* ```