4

I'm trying to understand the behaviour of DataWeave v1.0 when it comes to mapping objects in a root JSON array.

At this stage I just want to map each item in the array as-is without mapping each individual field of the item. I need to do it for each item in the array because later on I want to edit some of the fields, but since there are potentially many I don't want the overhead of mapping them one-by-one.

This is my dataweave:

%dw 1.0
%output application/json
---
payload map {
    ($)
}

This is my input:

[
  {
    "MyString": "ABCD",
    "MyNumber": 123,
    "AnObject": {
       "MyBool": false,
       "MyNestedObject": {
            "MyNestedString": "DEF"
       }
    }
  }
]

I want my output to be (at this stage) exactly the same as my input.

Instead my (wrong) output is:

[
  {
    "MyString": "ABCD",
    "MyNumber": 123,
    "MyBool": false,
    "MyNestedObject": {
      "MyNestedString": "DEF"
    }
  }
]

As you can see the object AnObject is missing, although its children remain.

Things are worse if the input includes arrays, for example the input:

[
  {
    "MyString": "ABCD",
    "MyNumber": 123,
    "AnObject": {
       "MyBool": false,
       "MyNestedObject": {
            "MyNestedString": "DEF"
       }
    },
    "AnArray": [
        {
            "Title": "An array item",
            "Description": "Pretty standard"
        }
    ]
  }
]

Throws the error:

Cannot coerce a :array to a :object.

I have played around with the mapObject operation on the root array items too, but I always run into the same behaviour. Is anyone able to explain what is happening here, and show me how I can copy each item in the root payload across dynamically.

Mule runtime is 3.9.1.

4

1 回答 1

1

要遍历数组中的每个项目并让它们保持原样,您应该这样做payload map $,这与payload map ((item) -> item)

您所做的与以下内容相同:payload map ((item) -> {(item)}).

在这里,您为每个项目返回的是{(expr)}在 Mule 3.9.1 上运行的 DW 版本中的表达式,它有一个意外行为,表达式试图强制expr(在这种情况下是一个对象)到对象数组,然后它将尝试展平父对象内该强制数组中的所有对象。看起来也试图强制键的值,这就是 DW 抛出错误的原因。

这种行为{()}在较新版本的 DW 中有所改变。

于 2019-07-05T18:54:36.490 回答