Переименование и удаление атрибутов в одном массиве с помощью dataweave - PullRequest
2 голосов
/ 21 января 2020

Мой пример полезной нагрузки приведен ниже:

{
  "entities": [
{
  "Id": "ab5fdd89e123",
  "target": {
    "Data": {
      "attributes": {
        "Name": [],
        "Address": [
          {
            "value": {
              "AddType": [{"value": "MAIN"}],
              "Flag": [{"value": true }]
                     }
}]}}}}]}

Мне нужно заменить атрибут с именем Flag (target.Data.attributes.Address.value.Flag) на «PrimaryFlag» со значением true. Мне также нужно добавить новый атрибут после того, как он называется «Код» со значением как ноль. Требуемый вывод должен быть таким, как показано ниже:

{
  "entities": [
    {
      "Id": "ab5fdd89e123",
      "target": {
        "Data": {
          "attributes": {
            "Name": [],
            "Address": [
              {
                "value": {
                  "AddType": [{"value": "MAIN"}],
                  "PrimaryFlag": [{"value": true }],
                  "Code": [{"value": null}]
                         }
}]}}}}]}

Я использую Mule 3.9 и использую dataweave 1.0

Ответы [ 2 ]

3 голосов
/ 21 января 2020

Попробуйте - это содержит комментарии:

%dw 1.0
%output application/dw
%var data = {
    "entities": [
        {
            "Id": "ab5fdd89e123",
            "target": {
                "Data": {
                    "attributes": {
                        "Name": [],
                        "Address": [
                            {
                                "value": {
                                    "AddType": [
                                        {
                                            "value": "MAIN"
                                        }
                                    ],
                                    "Flag": [
                                        {
                                            "value": true
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            }
        }
    ]
}

// Traverse a data structure
// When you traverse an object:
//   1) Get the fields as strings
//   2) Test whether you have a field Flag in your fields
//   3) If you do then rename Flag to PrimaryFlag and add 
//      the Code field to the current object
//      Traversal stops at this point
//   4) If you don't then just traverse object and recursivelly
//      traverse the values
// When you traverse an array:
//   1) Iterate over the array
//   2) Traverse every single element in the array
// For all other types default will execute.
%function traverse(ds) ds match {
    :object -> using (
        fs = $ pluck $$ as :string
    ) (
        (
            $ - "Flag" ++ {PrimaryFlag: $.Flag,Code: [{code: null}]} 
            when (fs contains "Flag")
            otherwise ($ mapObject {($$): traverse($)})
        )
    ),
    :array -> $ map traverse($),
    default -> $
}

---
traverse(data)

Мне пришлось сделать некоторые предположения, например, поле Flag не вложено в вашу структуру данных.

1 голос
/ 23 января 2020

Это должно позволить вам переименовать Flag в PrimaryFlag, а также добавить Code: [{code: null}] в качестве дочернего поля к attributes

%dw 1.0
%output application/dw
%var data = {
    "entities": [
        {
            "Id": "ab5fdd89e123",
            "target": {
                "Data": {
                    "attributes": {
                        "Name": [],
                        "Address": [
                            {
                                "value": {
                                    "AddType": [
                                        {
                                            "value": "MAIN"
                                        }
                                    ],
                                    "Flag": [
                                        {
                                            "value": true
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            }
        }
    ]
}

// Traverse a data structure
// When you traverse an object:
// 1) iterate over the fields and values using the mapObject operator
// 2) If the field is "Flag" then rename it to PrimaryFlag
// 3) If the field is "attributes" then add the {Code: [value: null]}
//    as a child node otherwise add the empty object, which will leave
//    the original object unchanged
// When you traverse an array:
//   1) Iterate over the array
//   2) Traverse every single element in the array
// For all other types default will execute.
%function traverse(ds) ds match {
    :object -> $ mapObject {
            (
                "PrimaryFlag" when ($$ as :string == "Flag") otherwise $$
            ): traverse($) ++ ({Code: [value: null]} when ($$ as :string == "attributes") otherwise {})
    },
    :array -> $ map traverse($),
    default -> $
}

---
traverse(data)

Эта версия продолжает повторяться и go в конец твоего дерева.

...