【问题标题】:How can I transform an array of objects to an array of strings and not lose the key in Dataweave?如何将对象数组转换为字符串数组而不丢失 Dataweave 中的键?
【发布时间】:2018-10-31 08:55:24
【问题描述】:

您好,我需要转换以下 JSON 对象:

{
  "products": [
    {
      "itemno": "123131",
      "description" : "Big Widget",
      "attributes": [
        {
          "color": [
            {
              "value": "Red",
              "codeValue": "RED_NO2"
            },
            {
              "value": "Blue Licorice",
              "codeValue": "BLUE-355"
            }
          ]
        },
        {
          "chemicals": [
            {
              "value": "Red Phosphorous",
              "codeValue": "RED_PHOS"
            },
            {
              "value": "Chlorine Bleach",
              "codeValue": "CHLRN_BLCH"
            }
          ]
        }
      ]
    }
  ]
}

我试图用每个属性来转换它,每个属性都有一个值数组,其中它们的值是 codeValue,它是这些字符串值的数组。

这是所需的输出:

{
  "products": [
    {
      "itemno": "123131",
      "description: : "Big Widget",
      "attributes": [
        {
          "color": ["RED_NO2", "BLUE-355"]
        },
        {
          "chemicals": ["RED_PHOS", "CHLRN_BLCH"]
        }
      ]
    }
  ]
}

这是数据编织。我无法确定如何获取属性名称(即颜色、化学物质作为具有所需数据的键。

关于使用 Dataweave 转换数据的好例子并不多,我花了很多时间试图弄清楚这一点。

这是其中一种数据编织,但不是解决方案:

%dw 1.0
%output application/json
---
payload.products map 
{
    "ItemNo" : $.sku,
    "Desc" : $.description,
    "Test" : "Value",
    "Attributes" : $.attributes map
    {
        '$$' : $ pluck $.value
    }
}

非常感谢您的帮助。

【问题讨论】:

  • 注意:在dataweave上面的“$.value”应该是“$.codeValue”

标签: mule dataweave


【解决方案1】:

你可以这样做:

%dw 1.0
%output application/json

%function attributeCodeValues(attributes)
  attributes map ((attr) -> 
    attr mapObject ((values, descriptor) ->
      {
        (descriptor): values map $.codeValue
      }
    )
  )
---
payload.products map {
    "ItemNo" : $.sku,
    "Desc" : $.description,
    "Test" : "Value",
    "Attributes" : attributeCodeValues($.attributes)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2022-10-07
    • 2022-01-06
    • 2017-05-20
    • 1970-01-01
    • 2011-12-27
    相关资源
    最近更新 更多