Это старая версия документа!


%dw 2.0
input payload json
output application/java
---
payload
%dw 2.0
output application/dw
---
payload
  • countBy Counts the elements in an array that return true when the matching function is applied to the value of each element.
  • divideBy Breaks up an array into sub-arrays that contain the specified number of elements.
  • drop Drops the first n elements. It returns the original array when n ⇐ 0 and an empty array when n > sizeOf(array).
  • dropWhile Drops elements from the array while the condition is met but stops the selection process when it reaches an element that fails to satisfy the condition.
  • every Returns true if every element in the array matches the condition.
  • firstWith Returns the first element that satisfies the condition, or returns null if no element meets the condition.
  • indexOf Returns the index of the first occurrence of an element within the array. If the value is not found, the function returns -1.
  • indexWhere Returns the index of the first occurrence of an element that matches a condition within the array. If no element matches the condition, the function returns -1.
  • join Joins two arrays of objects by a given ID criteria.
  • leftJoin Joins two arrays of objects by a given ID criteria.
  • outerJoin Joins two array of objects by a given ID criteria.
  • partition Separates the array into the elements that satisfy the condition from those that do not.
  • slice Selects the interval of elements that satisfy the condition: from ⇐ indexOf(array) < until
  • some Returns true if at least one element in the array matches the specified condition.
  • splitAt Splits an array into two at a given position.
  • splitWhere Splits an array into two at the first position where the condition is met.
  • sumBy Returns the sum of the values of the elements in an array.
  • take Selects the first n elements. It returns an empty array when n ⇐ 0 and the original array when n > sizeOf(array).
  • takeWhile Selects elements from the array while the condition is met but stops the selection process when it reaches an element that fails to satisfy the condition.

distinctBy

Выполняет итерацию по массиву и возвращает уникальные элементы в нем. DataWeave использует результат применения предоставленной лямбды в качестве критерия уникальности. Эта версия DifferentBy находит уникальные значения в массиве. Другие версии действуют на объект и обрабатывают нулевое значение.

Эта функция полезна, когда вам нужно удалить повторяющиеся элементы из массива

%dw 2.0
output json
---
payload distinctBy $.id

Filter Arrays

%dw 2.0
output application/json
---
{
    id: payload.Id,
    markCode: payload.marketCode,
    languageCode: payload.languageCode,
    username: payload.profile.base.username,
    phoneNumber: (payload.profile.base.phone filter ($.activeInd == "Y" and $.primaryInd== "Y")).number default []
}

Infix Notation: Long-Hand

[ ] filter (value, index) -> (condition)  

Infix Notation: $ syntax

[ ] filter (<condition using $, $$>) 

Prefix Notation

filter([ ], (value, index) -> (condition))

Filter Expression

[ ]  [? (<boolean_expression>) ]
%dw 2.0
output application/json
---
["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL"]
filter 
(value) -> (value contains "GO")
%dw 2.0
output application/json
---
["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL"]
filter
(value, index) -> ((index mod 2) == 0)
%dw 2.0
output application/json
---
["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL", "V", "COST"] filter ($endsWith("A"))
%dw 2.0
output application/json
---
payload
filter
(value, index) -> ((value.cik_str mod 2) == 1) and
(index > 5) and
(value.ticker startsWith  ("T"))
%dw 2.0
output application/json
---
["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL", "V", "COST"] [?( $ contains "GO" )]
Инфиксная запись / Infix Notation

Когда вы пишете арифметическое выражение, такое как B * C, форма выражения предоставляет вам информацию, позволяющую правильно его интерпретировать. В этом случае мы знаем, что переменная B умножается на переменную C, поскольку между ними в выражении появляется оператор умножения *. Этот тип записи называется инфиксным , поскольку оператор находится между двумя операндами, над которыми он работает.

До сих пор мы вызывали фильтр, используя префиксную запись. При использовании префиксной записи имя функции помещается перед аргументами. Если функция принимает два аргумента, как это делает фильтр, DataWeave позволяет вызывать ее с инфиксной записью.

Обратите внимание на дополнительные круглые скобки вокруг первой лямбды. Круглые скобки вокруг лямбда-выражений помогают DataWeave определить, где начинается и заканчивается лямбда-выражение.
%dw 2.0
output json

var numbers = (1 to 5)
---
numbers filter ((n, idx) -> (n mod 2) == 1)
%dw 2.0
output json

var numbers = (1 to 5)
---
numbers
  filter ((n, idx) -> (n mod 2) == 1)
  filter ((n, idx) -> (n > 3))
%dw 2.0
output json
---
[ ] filter (value, index) -> (condition)
%dw 2.0
output json
---
[ ] filter (<condition using $, $$>) 
Prefix Notation
%dw 2.0
output json
---
filter([ ], (value, index) -> (condition))

filterObject

Оператор filterObject перебирает список пар ключ-значение в объекте и применяет выражение, которое возвращает только соответствующие объекты, отфильтровывая остальные из выходных данных. Выражение должно возвращать значение true или false. Если выражение возвращает true ключ, значение или индекс объекта, объект фиксируется в выходных данных. Если он возвращает false какой-либо из них, объект отфильтровывается из вывода. Если совпадений нет, выходной массив будет пустым.

Infix Notation: Long-Hand

{ } filterObject (value,  key, index) -> (condition)

Infix Notation: $ syntax

{ } filterObject (condition with $, $$ , $$$ syntax) 

Prefix Notation

filterObject({ }, (value, index) -> (condition))

Filter Expression

{ } [? (<boolean_expression>) ]
%dw 2.0
output json
---
payload filterObject (value, key, index) -> key == "age"
%dw 2.0
output json
---
payload filterObject (value, key, index) -> key~="age"
%dw 2.0
output application/json
var myObject = {
    str1 : "String 1",
    str2 : "String 2",
    str3 : null,
    str4 : "String 4",
}
---
myObject filterObject $ != null
%dw 2.0
output application/json
---
payload
filterObject
(value, key, index) -> ((value.ticker contains "GO"))
Filter object by key 

%dw 2.0
output application/json
---
payload
filterObject
(value, key, index) -> (((key as Number) mod 2) == 0)
Filter object by index

%dw 2.0
output application/json
---
payload
filterObject
(value, key, index) -> (((index) mod 2) == 0)
Filter object by value with $ syntax 

%dw 2.0
output application/json
---
payload
filterObject
$ is Object
%dw 2.0
output application/json
---
payload
filterObject
$ is Array
Filter object by key with $$ syntax 

%dw 2.0
output application/json
---
payload
filterObject
((($$ as Number) mod 2) == 0)
Filter object by index with $$$ syntax 

%dw 2.0
output application/json
---
payload
filterObject
(($$$ mod 2) == 0)
Filter object using the filter expression selector

%dw 2.0
output application/json

---
payload [?( $.ticker contains "GO" )]

flatten

Для перемещения элементов из подмассивов в родительский массив, удаления подмассивов и преобразования всех пар ключ-значение в список объектов в родительском массиве. С помощью функции Flatten несколько массивов объединяются в один массив.

  • items The input array of arrays made up of any supported types.
%dw 2.0
output application/json
---
flatten(payload)
%dw 2.0
output application/json
var array1 = [1,2,3]
var array2 = [4,5,6]
var array3 = [7,8,9]
var arrayOfArrays = [array1, array2, array3]
---
flatten(arrayOfArrays)

groupBy

Функция groupBy принимает список объектов [x1,…,xn] и некоторую функцию f. Затем она отображает f в списке, давая список объектов [f(x1),…,f(xn)], и использует эти значения для выполнения операции groupBy. Эта функция полезна для группировки элементов массива на основе некоторого значения, которое генерируется из каждого элемента массива.

%dw 2.0
output json
---
payload groupBy (n, idx) -> isEven(n)
%dw 2.0
output json
---
payload groupBy (n, idx) -> n.dayOfWeek
%dw 2.0
output application/json
var user = {"firstName": "Manik", "lastName": "Magar", "Address Line1" : "Address line 1"}
---
user groupBy ((value, key) -> if (key contains 'Name') "Names" else "Address")

map

Функция карты используется для преобразования данных, содержащихся в массиве. Это делается путем перебора элементов массива и применения преобразования к каждому элементу. Результат преобразования собирается вместе и выводится в виде массива преобразованных элементов.

Перебирает элементы массива и выводит результаты в новый массив.

%dw 2.0
output application/json
---
{
    "candidatedetails": payload.employee map((item,index) -> {
        "fname":item.FirstName ++ " " ++ item.LastName
    })
}
%dw 2.0
output json
---
payload map (n, idx) -> n + 1
%dw 2.0
output json
---
payload.items.*name map (
    (item, index) -> {name: item}
)
%dw 2.0
var myVar = [
  { bookId: 101,
    title: "world history",
    price: "19.99"
  },
  {
    bookId: 202,
    title: 'the great outdoors',
    price: "15.99"
  }
]
var myVar2 = [
  {
    bookId: 101,
    author: "john doe"
  },
  {
    bookId: 202,
    author: "jane doe"
  }
]
output application/json
---
myVar map (item, index) -> using (id = item.bookId) {
	"id" : id,
	"topic" : item.title,
	"cost" : item.price as Number,
	(myVar2 filter ($.*bookId contains id) map (item) -> {
		author : item.author
	})
}

mapObject

Функция mapObject используется для преобразования данных, содержащихся в объекте. Это делается путем перебора каждой пары ключ/значение в объекте и применения преобразования к каждому ключу и значению. Он принимает объект и лямбду, которая принимает 3 параметра: значение, ключ и индекс, и возвращает новый объект. Наконец, вся функция возвращает объект.

%dw 2.0
output application/json
---
{"a":"b","c":"d"} mapObject (value,key,index) -> { (index) : { (value):key} }
%dw 2.0
output json
---
payload mapObject (value, key, index) -> {
  (upper(key)): value
}
%dw 2.0
output application/json
var user = {"firstName": "Manik", "lastName": "Magar", "addressLine1" : "Address line 1"}
var userList = [{"firstName": "Manik", "lastName": "Magar", "addressLine1" : "Address line 1"},
	{"firstName": "Om", "lastName": "Magar", "addressLine1" : "Address line 2"}
]
---
{
	mapObject: user mapObject (value:String, key:Key, index:Number) -> { 
		'$key-$index': value
	},

	pluck: user pluck (value, key, index) -> (key ++ '-' ++ index ++ '-' ++ value),    

	filter: user filterObject ((value, key, index) -> (index < 1)), 
	filter2: userList filter ((value, index) -> (index < 1)), 

	groupBy1 : user groupBy (value, key) -> key endsWith 'Name',    
	groupBy2 : userList groupBy ((value, index) -> value.lastName)   

}

pluck

это функция, используемая для преобразования свойств и значений этих свойств объекта в массив свойств, массив значений и массив индексов этих свойств. Эту функцию можно использовать, если вам нужно преобразовать объект в массив.

%dw 2.0
output json
---
payload pluck (v,k,idx) -> {(k): v}
%dw 2.0
output application/json
var requestBody= 
{
    "name":"Jack",
    "name":"James",
    "name":"Joseph"
}
---
{
    value: requestBody pluck $,
    keys: requestBody pluck $$,
    indexes: requestBody pluck $$$
}
%dw 2.0
output application/json
var requestBody= 
{
    "car": 
    {
        "Make&Model": "Maruti Suzuki Swift",
        "MakeYear": 2017,
        "Color": "Red",
        "Type": "Hatchback",
    },
    "car": 
    {
        "Make&Model": "Maruti WagonR",
        "MakeYear": 2018,
        "Color": "Brown",
        "Type": "Hatchback",
    },
    "car": 
    {
        "Make&Model": "Honda City",
        "MakeYear": 2017,
        "Color": "Red",
        "Type": "Sedan",
    },
    "car": 
    {
        "Make&Model": "Ford Figo",
        "MakeYear": 2017,
        "Color": "Black",
        "Type": "Hatchback",
    }
}
---
car:requestBody pluck $ filter $.Color == "Red"

reduce

Функция уменьшения используется для выполнения любых вычислений во время итерации массива, поэтому результат вычислений не теряется во время итерации. Для каждого элемента входного массива по порядку сокращение применяет лямбда-выражение (функцию) сокращения, а затем заменяет аккумулятор новым результатом. Лямбда-выражение может использовать как текущий элемент входного массива, так и текущее значение аккумулятора.

%dw 2.0
output json
---
payload reduce (n, total) -> total + n
%dw 2.0
output application/json
---
[2, 3] reduce ($ + $$)

Here

    [2,3] – is the input array
    acc -> $$ will take the 1st item value = 2 (as acc is not initialized)
    $ will take the 2nd item value = 3 (as acc is not initialized)
    Loop count = no of item in array minus 1 (as acc is not initialized) = 2 – 1 = 1
        Acc = ($=3 + $$=2) = 5

So result will be 5
%dw 2.0
output application/json
---
[2,3] reduce ((item, acc = 4) -> acc + item)

Here

    [2,3] – is the input array
    acc will take the initialized value = 4
    item will take 1st item value = 2 (as acc is initialized)
    Loop count = no of item in array (as acc is initialized) = 2
        Acc = acc + item -> 4 + 2 -> 6
        Acc = acc + item -> 6 + 3 -> 9

So result will be 9

read

  • stringToParse The string or binary to read.
  • contentType A supported format (or content type). Default: application/dw.
  • readerProperties Optional: Sets reader configuration properties. For other formats and reader configuration properties, see Supported Data Formats.
%dw 2.0
output application/json
var inputData=
"name,age,salary
Joseph,34,3000
James,32,5000"
---
read(inputData,"application/csv")
%dw 2.0
var myVar = "Some, Body"
output application/json
---
read(myVar,"application/csv",{header:false})[0]
%dw 2.0
output application/xml
---
read('{ "hello" : "world" }','application/json')

splitBy

Разбивает строку на массив строк на основе входного значения или соответствует части этой входной строки. Он отфильтровывает соответствующую часть из возвращаемого массива. Строка или регулярное выражение Java, используемое для разделения строки. Если какая-то часть строки не соответствует, функция вернет исходную неразбитую строку в массиве.

Эта версия splitBy принимает регулярное выражение Java (регулярное выражение), соответствующее входной строке. Регулярное выражение может соответствовать любому символу во входной строке. Обратите внимание, что splitBy выполняет противоположную операцию joinBy.

  • text The input string to split.
  • regex A Java regular expression used to split the string. If it does not match some part of the string, the function will return the original, unsplit string in the array.
%dw 2.0
output application/json
---
{ "splitters" : {
   "split1" : "a-b-c" splitBy(/^*.b./),
   "split2" : "hello world" splitBy(/\s/),
   "split3" : "no match" splitBy(/^s/),
   "split4" : "no match" splitBy(/^n../),
   "split5" : "a1b2c3d4A1B2C3D" splitBy(/^*[0-9A-Z]/)
  }
}
%dw 2.0
output application/json
---
{ "splitters" : {
    "split1" : "a-b-c" splitBy("-"),
    "split2" : "hello world" splitBy(""),
    "split3" : "first,middle,last" splitBy(","),
    "split4" : "no split" splitBy("NO")
   }
}
%dw 2.0
output application/java
---
payload splitBy(" ")
%dw 2.0
output application/java
---
payload splitBy(/s/)
%dw 2.0
output application/json
---
"192.88.99.0/24" splitBy(/[.\/]/)
%dw 2.0
output application/json
---
"192.88.99.0" splitBy(".")
  • divideBy Breaks up an object into sub-objects that contain the specified number of key-value pairs.
  • entrySet Returns an array of key-value pairs that describe the key, value, and any attributes in the input object.
  • everyEntry Returns true if every entry in the object matches the condition.
  • keySet Returns an array of key names from an object.
  • mergeWith Appends any key-value pairs from a source object to a target object.
  • nameSet Returns an array of keys from an object.
  • someEntry Returns true if at least one entry in the object matches the specified condition.
  • takeWhile Selects key-value pairs from the object while the condition is met.
  • valueSet Returns an array of the values from key-value pairs in an object.

Selector Expressions (update Operator)

update оператор позволяет обновлять указанные поля структуры данных новыми значениями. Этот селектор соответствия может проверять совпадения с любым значением внутри объекта.

%dw 2.0
var myInput = {
    "name": "Ken",
    "lastName":"Shokida",
    "age": 30,
    "address": {
        "street": "Amenabar",
        "zipCode": "AB1234"
    }
}
output application/json
---
myInput update {
    case age at .age -> age + 1
    case s at .address.street -> "First Street"
}
%dw 2.0
output application/json
---
payload update {
    case s at .addresses[0] -> {
        "street": "Second Street",
        "zipCode": "ZZ123"
    }
}
%dw 2.0
output application/json
---
payload update {
    case name at .user.@name -> upper(name)
}
%dw 2.0
var theFieldName = "name"
output application/json
---
payload update {
    case s at ."$(theFieldName)" -> "Shoki"
}
%dw 2.0
output application/json
---
payload map ((user) ->
    user update {
        case name at .name if(name == "Ken") -> name ++ " (Leandro)"
        case name at .name if(name == "Tomo") -> name ++ " (Christian)"
    }
)
%dw 2.0
var myInput = [{"lastName": "Doe"}, {"lastName": "Parker", "name": "Peter" }]
output application/json
---
myInput  map ((value) ->
    value update {
        case name at .name! -> if(name == null) "JOHN" else upper(name)
    }
)
%dw 2.0
output application/json
---
payload update {
    //equivalent expression:
    //case age at .age -> age + 1
    case .age -> $ + 1
    case .address.street -> "First Street"
}
%dw 2.0
var myInput = {
    "name": "Ken",
    "lastName":"Shokida",
    "age": 30
}
output application/json
---
myInput mapObject ((value,key) ->
    if(key as String == "age")
       {(key): value as Number + 1}
    else
       {(key): value} )
%dw 2.0
var myInput = {
    "name": "Ken",
    "lastName":"Shokida",
    "age": 30
}
output application/json
---
myInput update {
    case age at .age -> age + 1
}
%dw 2.0
output application/json
---
payload map ((item) ->
    item.ServiceDetails update {
        case Designation at .Designation if (Designation == "Clerk") ->  "Assistant Manager"
})

Ссылки