You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Logic Apps基于键值对解析复杂JSON

在Logic Apps中基于键提取D365 Events JSON字段并写入SQL Server

针对你提出的需求,以下是无需依赖索引、完全基于键值对操作的实现方案,可有效避免schema drift问题,同时简化字段管理和SQL写入流程:

核心思路

通过Logic Apps内置的表达式和操作,直接根据JSON中的key值定位目标字段,将复杂嵌套的JSON转换为扁平结构,再映射到SQL Server进行写入。


步骤1:提取Target实体对象

首先从顶层JSON数组中获取key为"Target"的实体(如需处理PreImage,只需替换为"PreImage"):

  1. 添加初始化变量操作,变量类型选对象,名称设为var_TargetEntity
  2. 变量值使用以下表达式:
    first(where(triggerBody(), 'key', 'Target')).value
    
    该表达式通过where()过滤出key为Target的项,再用first()取唯一匹配的实体对象。

步骤2:基于键提取字段值

针对每个需要提取的字段,使用键值查找表达式获取对应值,无需依赖数组索引:

普通字符串/数字字段(如mserp_customeraccount)

表达式示例:

first(where(variables('var_TargetEntity')?['Attributes'], 'key', 'mserp_customeraccount')).value

OptionSet类型字段(如mserp_organizationabccode)

需提取嵌套的Value属性:

first(where(variables('var_TargetEntity')?['Attributes'], 'key', 'mserp_organizationabccode')).value.Value

FormattedValues中的字段(如mserp_dataareaid_id)

表达式示例:

first(where(variables('var_TargetEntity')?['FormattedValues'], 'key', 'mserp_dataareaid_id')).value

处理缺失字段(可选)

若担心字段不存在导致报错,可使用coalesce()设置默认值:

coalesce(first(where(variables('var_TargetEntity')?['Attributes'], 'key', 'mserp_knownas')).value, '')

可选优化:存储为单独变量

将每个字段的提取结果存入单独变量(如var_CustomerAccount、var_OrganizationName),便于后续SQL操作时快速引用。


步骤3:转换为扁平结构(可选)

使用选择操作将所需字段整合为一个扁平JSON对象,简化SQL映射:

  1. 添加选择操作,来自设为variables('var_TargetEntity')
  2. 在映射区域添加所需字段,例如:
    • 客户账号: first(where(item()?['Attributes'], 'key', 'mserp_customeraccount')).value
    • 组织名称: first(where(item()?['Attributes'], 'key', 'mserp_organizationname')).value
    • ABC编码: first(where(item()?['Attributes'], 'key', 'mserp_organizationabccode')).value.Value
    • 数据区域ID: first(where(item()?['FormattedValues'], 'key', 'mserp_dataareaid_id')).value

步骤4:写入SQL Server

添加**插入行(SQL Server)**操作,将提取的字段直接映射到SQL表的对应列:

  • 若使用了单独变量:直接选择变量作为列值
  • 若使用了选择操作:选择扁平对象中的对应字段作为列值

关键优势

  • 避免schema drift:完全基于key值查找,不受JSON数组中字段顺序变化影响
  • 低维护成本:无需循环过滤,通过直接表达式定位字段,逻辑清晰
  • 兼容性强:支持普通字段、OptionSet、FormattedValues等多种类型的字段提取

内容的提问来源于stack exchange,提问作者TePeBox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 22:25:54