Различия
Показаны различия между двумя версиями страницы.
Предыдущая версия справа и слева Предыдущая версия Следующая версия | Предыдущая версия | ||
develop:mule:dataweave [2024/02/19 00:56] – mirocow | develop:mule:dataweave [2024/03/06 22:19] (текущий) – [Ссылки] mirocow | ||
---|---|---|---|
Строка 1: | Строка 1: | ||
- | {{tag> | + | {{tag> |
- | ====== DataWeave | + | ===== DataWeave ===== |
<code dw> | <code dw> | ||
Строка 18: | Строка 18: | ||
</ | </ | ||
- | ===== mapObject | + | <note tip>IDE https:// |
+ | ===== Oprators | ||
- | Функция | + | * using: For initializing local variables in a DataWeave script. |
+ | * Unary DataWeave operators at this level: | ||
+ | * .^: Schema selector. | ||
+ | * .#: Namespace selector. | ||
+ | * ..: Descendants selector. | ||
+ | * not: Logical operator for negation. | ||
+ | * .@: All attribute selector, for example, in a case that uses the expression payload.root.a.@ to return the attributes and values of the input payload < | ||
+ | ==== Condition ==== | ||
< | < | ||
Строка 26: | Строка 34: | ||
output application/ | output application/ | ||
--- | --- | ||
- | {"a":" | + | { |
+ | | ||
+ | } | ||
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output json | + | var myVar = { country : " |
+ | output | ||
--- | --- | ||
- | payload mapObject | + | if (myVar.country == " |
- | | + | |
- | } | + | else { currency: " |
</ | </ | ||
Строка 41: | Строка 52: | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
- | var user = {" | + | var user = {" |
- | var userList = [{" | + | |
- | {" | + | |
- | ] | + | |
--- | --- | ||
- | { | + | name : user mapObject { |
- | mapObject: user mapObject | + | (' |
- | '$key-$index': | + | |
- | }, | + | |
- | + | ||
- | pluck: user pluck (value, key, index) -> (key ++ '-' | + | |
- | + | ||
- | filter: user filterObject | + | |
- | filter2: userList filter ((value, index) -> (index < 1)), | + | |
- | + | ||
- | groupBy1 : user groupBy (value, key) -> key endsWith | + | |
- | groupBy2 : userList groupBy ((value, index) -> value.lastName) | + | |
} | } | ||
</ | </ | ||
- | |||
- | |||
- | ===== Working with Objects / dw:: | ||
- | |||
- | * **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. | ||
- | |||
- | ===== Working with Arrays / dw:: | ||
- | |||
- | * **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. | ||
- | |||
- | |||
- | |||
- | ===== reduce ===== | ||
- | |||
- | Функция уменьшения используется для выполнения любых вычислений во время итерации массива, | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | var aRecord = |
+ | [ | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | ] | ||
+ | output | ||
--- | --- | ||
- | payload reduce | + | { examples: |
+ | { | ||
+ | ex1 : if (1 + 1 == 55) true | ||
+ | else false, | ||
+ | ex2 : if ([1, | ||
+ | else "value of index 1 is not 1", | ||
+ | ex3 : if (isEmpty(aRecord.bookId)) "ID is empty" | ||
+ | else "ID is not empty", | ||
+ | ex4 : aRecord.bookId map (idValue) -> | ||
+ | if (idValue as Number == 101) idValue as Number | ||
+ | else "not 101" | ||
+ | } | ||
+ | } | ||
</ | </ | ||
Строка 113: | Строка 87: | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
+ | var user = {" | ||
--- | --- | ||
- | [2, 3] reduce | + | name : user filter |
+ | </ | ||
- | Here | + | ==== Filters ==== |
- | [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/ | ||
- | --- | ||
- | [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 | + | ==== Functions ==== |
- | </ | + | |
- | ===== groupBy ===== | + | * Named functions |
+ | * Lambdas | ||
+ | * Passing functions to other functions | ||
+ | * Calling 2-arity functions with infix notation | ||
+ | * $, $$, $$$ syntax | ||
- | Функция groupBy принимает список объектов [x1,…,xn] и некоторую функцию f. Затем она отображает f в списке, | + | === Лямда функции |
- | < | + | Полезность лямбд становится очевидной, когда мы объединяем две идеи: |
- | %dw 2.0 | + | |
- | output json | + | |
- | --- | + | |
- | payload groupBy (n, idx) -> isEven(n) | + | |
- | </ | + | |
- | < | + | * Лямбды — это значения, |
- | %dw 2.0 | + | * Значения могут передаваться функциям в качестве аргументов, а также возвращаться из функций. |
- | output json | + | |
- | --- | + | |
- | payload groupBy (n, idx) -> n.dayOfWeek | + | |
- | </ | + | |
- | < | + | В DataWeave функции и лямбды |
- | %dw 2.0 | + | |
- | output application/ | + | |
- | var user = {" | + | |
- | --- | + | |
- | user groupBy | + | |
- | </ | + | |
- | ===== distinctBy ===== | + | |
- | Выполняет | + | DataWeave |
- | Эта функция полезна, когда вам нужно удалить повторяющиеся элементы из массива | + | <note tip> |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
- | --- | ||
- | payload distinctBy $.id | ||
- | </ | ||
- | ===== map ===== | + | fun isOddNum(n) |
+ | (n mod 2) == 1 | ||
- | Функция карты используется для преобразования данных, содержащихся в массиве. Это делается путем перебора элементов массива и применения преобразования к каждому элементу. Результат преобразования собирается вместе и выводится в виде массива преобразованных элементов. | + | // Generate [1, 2, ..., 5] |
- | + | var numbers = (1 to 5) | |
- | Перебирает элементы массива и выводит результаты в новый массив. | + | |
- | + | ||
- | < | + | |
- | %dw 2.0 | + | |
- | output application/ | + | |
--- | --- | ||
- | { | + | filter(numbers, |
- | " | + | |
- | " | + | |
- | }) | + | |
- | } | + | |
</ | </ | ||
Строка 203: | Строка 136: | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
+ | |||
+ | var numbers = (1 to 5) | ||
--- | --- | ||
- | payload map (n, idx) -> n + 1 | + | filter(numbers, |
</ | </ | ||
Строка 211: | Строка 146: | ||
output json | output json | ||
--- | --- | ||
- | payload.items.*name map ( | + | (() -> 2 + 3)() |
- | | + | |
- | ) | + | |
</ | </ | ||
< | < | ||
- | |||
%dw 2.0 | %dw 2.0 | ||
- | var myVar = [ | ||
- | { bookId: 101, | ||
- | title: "world history", | ||
- | price: " | ||
- | }, | ||
- | { | ||
- | bookId: 202, | ||
- | title: 'the great outdoors', | ||
- | price: " | ||
- | } | ||
- | ] | ||
- | var myVar2 = [ | ||
- | { | ||
- | bookId: 101, | ||
- | author: "john doe" | ||
- | }, | ||
- | { | ||
- | bookId: 202, | ||
- | author: "jane doe" | ||
- | } | ||
- | ] | ||
output application/ | output application/ | ||
+ | var toUser = (user) -> { | ||
+ | firstName: user.field1, | ||
+ | lastName: user.field2 | ||
+ | } | ||
--- | --- | ||
- | myVar map (item, index) -> using (id = item.bookId) | + | { |
- | "id" : id, | + | "user" : toUser(payload) |
- | " | + | |
- | " | + | |
- | (myVar2 filter ($.*bookId contains id) map (item) -> { | + | |
- | author : item.author | + | |
- | }) | + | |
} | } | ||
</ | </ | ||
- | ===== pluck ===== | + | === Логические операторы / Logical Operators |
- | это функция, используемая для преобразования свойств и значений этих свойств объекта в массив свойств, массив значений и массив индексов этих свойств. Эту функцию можно использовать, если вам нужно преобразовать объект в массив. | + | * A > B Greater than |
+ | * A < B Less than | ||
+ | * A >= B Greater than or equal to | ||
+ | * A <= B Less than or equal to | ||
+ | * A == B Equal to | ||
+ | * A != B Not equal to | ||
+ | * A ~= B Similar to | ||
+ | * not A Logical negation | ||
+ | * !A Logical negation | ||
+ | * A and B Logical and | ||
+ | * A or B Logical or | ||
+ | * not Negates the result of the input. See also, !. | ||
+ | * ! Negates the result of the input. See also, not. Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later. | ||
+ | * and Returns true if the result of all inputs is true, false if not. | ||
+ | * or Returns true if the result of any input is true, false if not. | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
+ | var age = 2 | ||
--- | --- | ||
- | payload pluck (v,k,idx) -> {(k): v} | + | age < 10 |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | var myArray = [1,2,3,4,5] | ||
+ | var myMap = myArray map not (($ mod 2) == 0) | ||
output application/ | output application/ | ||
- | var requestBody= | ||
- | { | ||
- | " | ||
- | " | ||
- | " | ||
- | } | ||
--- | --- | ||
{ | { | ||
- | value: requestBody pluck $, | + | " |
- | keys: requestBody pluck $$, | + | " |
- | indexes: requestBody pluck $$$ | + | " |
+ | " | ||
+ | ], | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | ], | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | ], | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | ] | ||
} | } | ||
</ | </ | ||
Строка 282: | Строка 219: | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | var orNot = if (1 + 1 == 4 or not 1 == 2) {" | ||
+ | else {" | ||
+ | var andNot = if (1 + 1 == 2 and not 1 == 2) {" | ||
+ | else {" | ||
+ | var notWithAndNot = if (not (1 + 1 == 2 and not 1 == 1)) {" | ||
+ | else {" | ||
output application/ | output application/ | ||
- | var requestBody= | + | --- |
- | { | + | { "answers" : |
- | "car" : | + | [ |
- | { | + | orNot, |
- | " | + | |
- | " | + | |
- | " | + | ] |
- | " | + | |
- | }, | + | |
- | " | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | }, | + | |
- | " | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | }, | + | |
- | " | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
} | } | ||
- | } | ||
- | --- | ||
- | car: | ||
</ | </ | ||
- | ===== Selector Expressions (update Operator) | + | === Types === |
- | + | ||
- | update оператор позволяет обновлять указанные поля структуры данных новыми значениями. | + | |
- | Этот селектор соответствия может проверять совпадения с любым значением внутри объекта. | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myInput = { | ||
- | " | ||
- | " | ||
- | " | ||
- | " | ||
- | " | ||
- | " | ||
- | } | ||
- | } | ||
output application/ | output application/ | ||
--- | --- | ||
- | myInput update | + | { |
- | case age at .age -> age + 1 | + | /* |
- | case s at .address.street | + | * A multi-line |
+ | * comment here. | ||
+ | */ | ||
+ | myString: "hello world", | ||
+ | myNumber: 123, | ||
+ | myFloatingPointNumber: | ||
+ | myVeryBigNumber: | ||
+ | myDate: |2018-12-07|, | ||
+ | myTime: |11: | ||
+ | myDateTime: |2018-10-01T23: | ||
+ | myBoolean: true, | ||
+ | myArray: [ 1, 2, 3, 5, 8], | ||
+ | myMixedArray: | ||
+ | myObjectKeyValuePair: | ||
+ | myObjectWithConditionalField: | ||
+ | myNull: null, | ||
+ | myBinary: " | ||
+ | //A one-line comment here. | ||
} | } | ||
</ | </ | ||
+ | ===== dw::* ===== | ||
- | <code> | + | ==== dw:: |
- | %dw 2.0 | + | |
- | output application/ | + | * **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. |
- | payload update { | + | * **drop** Drops the first n elements. It returns the original array when n <= 0 and an empty array when n > sizeOf(array). |
- | case s at .addresses[0] -> { | + | * **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 |
- | } | + | * **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 |
- | </code> | + | * **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. | ||
+ | |||
+ | === divideBy === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | import divideBy from dw:: | ||
output application/ | output application/ | ||
--- | --- | ||
- | payload update | + | { " |
- | case name at .user.@name -> upper(name) | + | |
- | } | + | |
</ | </ | ||
+ | === drop === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var theFieldName | + | import * from dw:: |
+ | var samplearray | ||
output application/ | output application/ | ||
--- | --- | ||
- | payload update { | + | |
- | case s at ."$(theFieldName)" -> " | + | drop(samplearray, |
- | } | + | |
</ | </ | ||
+ | |||
+ | === indexOf === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | import * from dw:: | ||
+ | var samplearray = [" | ||
output application/ | output application/ | ||
--- | --- | ||
- | payload map ((user) -> | + | |
- | user update { | + | indexOf(samplearray, |
- | case name at .name if(name == "Ken") -> name ++ " (Leandro)" | + | |
- | case name at .name if(name == " | + | |
- | } | + | |
- | ) | + | |
</ | </ | ||
+ | |||
+ | === join === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myInput | + | import * from dw:: |
+ | |||
+ | var items = [{id: "12", name:"Tea"},{id: "22", name:"Salt"},{id: "3", | ||
+ | |||
+ | var Prices = [{Id: " | ||
+ | |||
output application/ | output application/ | ||
--- | --- | ||
- | myInput | + | join(items, Prices, |
- | value update { | + | |
- | case name at .name! -> if(name == null) " | + | |
- | } | + | |
- | ) | + | |
</ | </ | ||
+ | === takeWhile === | ||
+ | |||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | import * from dw:: | ||
output application/ | output application/ | ||
+ | var arr = [1, | ||
--- | --- | ||
- | payload update { | + | |
- | // | + | arr takeWhile |
- | //case age at .age -> age + 1 | + | |
- | case .age -> $ + 1 | + | |
- | case .address.street -> "First Street" | + | |
- | } | + | |
- | </ | + | |
- | < | ||
- | %dw 2.0 | ||
- | var myInput = { | ||
- | " | ||
- | " | ||
- | " | ||
- | } | ||
- | output application/ | ||
- | --- | ||
- | myInput mapObject ((value, | ||
- | if(key as String == " | ||
- | | ||
- | else | ||
- | | ||
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myInput = { | + | import * from dw::core::Objects |
- | " | + | |
- | " | + | |
- | " | + | |
- | } | + | |
output application/ | output application/ | ||
- | --- | + | var obj = { |
- | myInput update | + | " |
- | case age at .age -> age + 1 | + | " |
+ | " | ||
+ | " | ||
} | } | ||
- | </ | ||
- | |||
- | < | ||
- | %dw 2.0 | ||
- | output application/ | ||
--- | --- | ||
- | payload map ((item) -> | + | obj takeWhile |
- | item.ServiceDetails update { | + | |
- | case Designation at .Designation if (Designation == " | + | |
- | }) | + | |
</ | </ | ||
+ | ==== dw::Core ==== | ||
- | ===== flatten ===== | + | === distinctBy |
- | Для перемещения элементов из подмассивов в родительский массив, удаления | + | Выполняет итерацию по массиву и возвращает уникальные |
- | * **items** The input array of arrays made up of any supported types. | + | Эта функция полезна, |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output json |
--- | --- | ||
- | flatten(payload) | + | payload |
</ | </ | ||
Строка 465: | Строка 381: | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
- | var array1 | + | var str = [1,2,3,4,5,6,7] |
- | var array2 = [4,5,6] | + | var str1= [4,5,6,7,1] |
- | var array3 | + | |
- | var arrayOfArrays = [array1, array2, array3] | + | |
--- | --- | ||
- | flatten(arrayOfArrays) | + | (str ++ str1) distinctBy ((item, index) -> |
</ | </ | ||
- | ===== splitBy | + | === Filter Arrays |
- | + | ||
- | Разбивает строку на массив строк на основе входного значения или соответствует части этой входной строки. Он отфильтровывает соответствующую часть из возвращаемого массива. Строка или регулярное выражение Java, используемое для разделения строки. Если какая-то часть строки не соответствует, | + | |
- | + | ||
- | Эта версия splitBy принимает регулярное выражение Java (регулярное выражение), | + | |
- | + | ||
- | * **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. | + | |
< | < | ||
Строка 486: | Строка 393: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { " | + | { |
- | " | + | id: payload.Id, |
- | " | + | |
- | " | + | |
- | " | + | |
- | "split5" | + | |
- | } | + | |
} | } | ||
</ | </ | ||
+ | Infix Notation: Long-Hand | ||
< | < | ||
- | %dw 2.0 | + | [ ] filter |
- | output application/ | + | |
- | --- | + | |
- | { " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | } | + | |
- | } | + | |
</ | </ | ||
+ | Infix Notation: $ syntax | ||
< | < | ||
- | %dw 2.0 | + | [ ] filter |
- | output application/ | + | |
- | --- | + | |
- | payload splitBy(" ") | + | |
</ | </ | ||
+ | Prefix Notation | ||
< | < | ||
- | %dw 2.0 | + | filter([ ], (value, index) |
- | output application/ | + | |
- | --- | + | |
- | payload splitBy(/s/) | + | |
</ | </ | ||
+ | Filter Expression | ||
< | < | ||
- | %dw 2.0 | + | [ ] [? (< |
- | output application/ | + | |
- | --- | + | |
- | " | + | |
</ | </ | ||
Строка 534: | Строка 426: | ||
output application/ | output application/ | ||
--- | --- | ||
- | "192.88.99.0" | + | ["AAPL", " |
+ | filter | ||
+ | (value) -> (value contains | ||
</ | </ | ||
- | |||
- | ===== read ===== | ||
- | |||
- | * **stringToParse** The string or binary to read. | ||
- | * **contentType** A supported format (or content type). Default: application/ | ||
- | * **readerProperties** Optional: | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
- | var inputData= | ||
- | " | ||
- | Joseph, | ||
- | James, | ||
--- | --- | ||
- | read(inputData,"application/ | + | [" |
+ | filter | ||
+ | (value, index) -> ((index mod 2) == 0) | ||
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myVar = "Some, Body" | ||
output application/ | output application/ | ||
--- | --- | ||
- | read(myVar,"application/ | + | [" |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output application/ | + | output application/ |
--- | --- | ||
- | read(' | + | payload |
+ | filter | ||
+ | (value, index) -> ((value.cik_str mod 2) == 1) and | ||
+ | (index > 5) and | ||
+ | (value.ticker startsWith | ||
</ | </ | ||
- | |||
- | ===== readUrl ===== | ||
- | |||
- | * **url** The URL string to read. It also accepts a classpath-based URL. for example: classpath: | ||
- | * **contentType** A supported format (or MIME type). Default: application/ | ||
- | * **readerProperties** Optional: | ||
< | < | ||
Строка 579: | Строка 462: | ||
output application/ | output application/ | ||
--- | --- | ||
- | readUrl("classpath:// | + | ["AAPL", "MSFT", " |
</ | </ | ||
- | < | ||
- | %dw 2.0 | ||
- | var myJsonSnippet = readUrl(" | ||
- | output application/ | ||
- | --- | ||
- | (myJsonSnippet.results map(item) -> item.profile) | ||
- | </ | ||
- | < | + | == Инфиксная запись |
- | %dw 2.0 | + | |
- | output application/json | + | |
- | --- | + | |
- | readUrl(" | + | |
- | </ | + | |
- | < | + | Когда вы пишете арифметическое выражение, такое как B * C, форма выражения предоставляет вам информацию, |
- | %dw 2.0 | + | |
- | output application/ | + | |
- | var inputData=readUrl(" | + | |
- | --- | + | |
- | { | + | |
- | name: inputData.name, | + | |
- | username: inputData.username, | + | |
- | email: inputData.email | + | |
- | } | + | |
- | </ | + | |
- | ===== Condition ===== | + | До сих пор мы вызывали фильтр, |
+ | |||
+ | <note tip> | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output json |
+ | |||
+ | var numbers = (1 to 5) | ||
--- | --- | ||
- | { | + | numbers filter |
- | " | + | |
- | } | + | |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myVar = { country : " | + | output json |
- | output | + | |
- | --- | + | |
- | if (myVar.country == " | + | |
- | { currency: " | + | |
- | else { currency: " | + | |
- | </ | + | |
- | < | + | var numbers |
- | %dw 2.0 | + | |
- | output application/ | + | |
- | var user = {" | + | |
--- | --- | ||
- | name : user mapObject { | + | numbers |
- | (' | + | |
- | } | + | |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var aRecord = | + | output |
- | [ | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | ] | + | |
- | output | + | |
--- | --- | ||
- | { examples: | + | [ ] filter (value, index) -> (condition) |
- | { | + | |
- | ex1 : if (1 + 1 == 55) true | + | |
- | else false, | + | |
- | ex2 : if ([1,2,3,4][1] == 1) 1 | + | |
- | else "value of index 1 is not 1", | + | |
- | ex3 : if (isEmpty(aRecord.bookId)) "ID is empty" | + | |
- | else "ID is not empty", | + | |
- | ex4 : aRecord.bookId map (idValue) -> | + | |
- | | + | |
- | else "not 101" | + | |
- | } | + | |
- | } | + | |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output json |
- | var user = {" | + | |
--- | --- | ||
- | name : user filter ($ contains " | + | [ ] filter (< |
</ | </ | ||
- | ===== Filters ===== | + | == Prefix Notation |
- | + | ||
- | ==== filter ==== | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output json |
--- | --- | ||
- | { | + | filter([ ], (value, index) -> (condition)) |
- | id: payload.Id, | + | |
- | markCode: payload.marketCode, | + | |
- | languageCode: | + | |
- | username: payload.profile.base.username, | + | |
- | phoneNumber: | + | |
- | } | + | |
</ | </ | ||
- | + | === filterObject === | |
- | ==== filterObject | + | |
Оператор | Оператор | ||
Строка 708: | Строка 534: | ||
Prefix Notation | Prefix Notation | ||
< | < | ||
- | filterOject({ }, (value, index) -> (condition)) | + | filterObject({ }, (value, index) -> (condition)) |
</ | </ | ||
Строка 790: | Строка 616: | ||
--- | --- | ||
payload | payload | ||
- | filterO | + | filterObject |
- | bject | + | |
$ is Array | $ is Array | ||
</ | </ | ||
Строка 826: | Строка 651: | ||
payload [?( $.ticker contains " | payload [?( $.ticker contains " | ||
</ | </ | ||
- | |||
- | ==== valuesOf ==== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output application/ | + | output application/ |
--- | --- | ||
- | valuesOf(payload.responses) filter | + | payload |
+ | | ||
+ | and (key as String != "last name" | ||
+ | ) | ||
</ | </ | ||
+ | === flatten === | ||
- | ==== Filter Arrays ==== | + | Для перемещения элементов из подмассивов в родительский массив, |
- | Infix Notation: Long-Hand | + | * **items** The input array of arrays made up of any supported types. |
- | < | + | |
- | [ ] filter (value, index) -> (condition) | + | |
- | </ | + | |
- | + | ||
- | Infix Notation: $ syntax | + | |
- | < | + | |
- | [ ] filter (< | + | |
- | </ | + | |
- | + | ||
- | Prefix Notation | + | |
- | < | + | |
- | filter([ ], (value, index) -> (condition)) | + | |
- | </ | + | |
- | + | ||
- | Filter Expression | + | |
- | < | + | |
- | [ ] [? (< | + | |
- | </ | + | |
< | < | ||
Строка 862: | Строка 671: | ||
output application/ | output application/ | ||
--- | --- | ||
- | [" | + | flatten(payload) |
- | filter | + | |
- | (value) -> (value contains " | + | |
</ | </ | ||
Строка 870: | Строка 677: | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
+ | var array1 = [1,2,3] | ||
+ | var array2 = [4,5,6] | ||
+ | var array3 = [7,8,9] | ||
+ | var arrayOfArrays = [array1, array2, array3] | ||
--- | --- | ||
- | [" | + | flatten(arrayOfArrays) |
- | filter | + | |
- | (value, index) -> ((index mod 2) == 0) | + | |
</ | </ | ||
+ | === groupBy === | ||
- | < | + | Функция groupBy |
- | %dw 2.0 | + | |
- | output application/ | + | |
- | --- | + | |
- | [" | + | |
- | </ | + | |
- | + | ||
- | < | + | |
- | %dw 2.0 | + | |
- | output application/ | + | |
- | --- | + | |
- | payload | + | |
- | filter | + | |
- | (value, index) -> ((value.cik_str mod 2) == 1) and | + | |
- | (index > 5) and | + | |
- | (value.ticker startsWith | + | |
- | </ | + | |
- | + | ||
- | < | + | |
- | %dw 2.0 | + | |
- | output application/ | + | |
- | --- | + | |
- | [" | + | |
- | </ | + | |
- | ===== Functions ===== | + | |
- | + | ||
- | * Named functions | + | |
- | * Lambdas | + | |
- | * Passing functions to other functions | + | |
- | * Calling 2-arity functions with infix notation | + | |
- | * $, $$, $$$ syntax | + | |
- | + | ||
- | ==== Инфиксная запись / Infix Notation ==== | + | |
- | + | ||
- | Когда вы пишете | + | |
- | + | ||
- | До сих пор мы вызывали фильтр, | + | |
- | + | ||
- | <note tip> | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
- | |||
- | var numbers = (1 to 5) | ||
--- | --- | ||
- | numbers filter ((n, idx) -> (n mod 2) == 1) | + | payload groupBy |
</ | </ | ||
Строка 928: | Строка 698: | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
- | |||
- | var numbers = (1 to 5) | ||
--- | --- | ||
- | numbers | + | payload groupBy |
- | filter ((n, idx) -> (n mod 2) == 1) | + | |
- | filter ((n, idx) -> (n > 3)) | + | |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output json | + | output |
+ | var user = {" | ||
--- | --- | ||
- | [ ] filter | + | user groupBy ((value, |
</ | </ | ||
- | < | + | === map === |
- | %dw 2.0 | + | |
- | output json | + | |
- | --- | + | |
- | [ ] filter (< | + | |
- | </ | + | |
- | ==== Prefix Notation | + | Функция карты используется для преобразования данных, |
+ | |||
+ | Перебирает элементы массива и выводит результаты в новый массив. | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output json | + | output |
--- | --- | ||
- | filter([ ], (value, index) -> (condition)) | + | { |
+ | " | ||
+ | " | ||
+ | }) | ||
+ | } | ||
</ | </ | ||
- | |||
- | ==== Лямда функции / Functions as Values ==== | ||
- | |||
- | Полезность лямбд становится очевидной, | ||
- | |||
- | * Лямбды — это значения, | ||
- | * Значения могут передаваться функциям в качестве аргументов, | ||
- | |||
- | В DataWeave функции и лямбды (анонимные функции) могут передаваться как значения или присваиваться переменным. | ||
- | |||
- | DataWeave предоставляет несколько способов создания функций. Точно так же, как у нас есть именованные функции, | ||
- | |||
- | <note tip> | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
- | |||
- | fun isOddNum(n) = | ||
- | (n mod 2) == 1 | ||
- | |||
- | // Generate [1, 2, ..., 5] | ||
- | var numbers = (1 to 5) | ||
--- | --- | ||
- | filter(numbers, | + | payload map (n, idx) -> n + 1 |
</ | </ | ||
Строка 988: | Строка 737: | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
- | |||
- | var numbers = (1 to 5) | ||
--- | --- | ||
- | filter(numbers, | + | payload.items.*name map ( |
+ | | ||
+ | ) | ||
</ | </ | ||
< | < | ||
- | %dw 2.0 | ||
- | output json | ||
- | --- | ||
- | (() -> 2 + 3)() | ||
- | </ | ||
- | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | var myVar = [ | ||
+ | { bookId: 101, | ||
+ | title: "world history", | ||
+ | price: " | ||
+ | }, | ||
+ | { | ||
+ | bookId: 202, | ||
+ | title: 'the great outdoors', | ||
+ | price: " | ||
+ | } | ||
+ | ] | ||
+ | var myVar2 = [ | ||
+ | { | ||
+ | bookId: 101, | ||
+ | author: "john doe" | ||
+ | }, | ||
+ | { | ||
+ | bookId: 202, | ||
+ | author: "jane doe" | ||
+ | } | ||
+ | ] | ||
output application/ | output application/ | ||
- | var toUser = (user) -> { | ||
- | firstName: user.field1, | ||
- | lastName: user.field2 | ||
- | } | ||
--- | --- | ||
- | { | + | myVar map (item, index) -> using (id = item.bookId) |
- | "user" : toUser(payload) | + | "id" : id, |
+ | " | ||
+ | " | ||
+ | (myVar2 filter ($.*bookId contains id) map (item) -> { | ||
+ | author : item.author | ||
+ | }) | ||
} | } | ||
</ | </ | ||
- | |||
- | ==== Именованные функции / Named Functions ==== | ||
- | |||
- | Для создания функции в разделе объявлений скрипта, | ||
- | |||
- | <note tip> | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output |
- | + | fun process(obj: Object) = obj mapObject ((value, key) -> { | |
- | fun add(n, m) = | + | |
- | n + m | + | case " |
+ | else -> value | ||
+ | } | ||
+ | }) | ||
--- | --- | ||
- | add(1,2) | + | payload map ((item, index) -> |
+ | process(item) | ||
+ | ) | ||
</ | </ | ||
+ | === mapObject === | ||
- | < | + | Функция |
- | %dw 2.0 | + | |
- | output json | + | |
- | + | ||
- | fun diff(n) = do { | + | |
- | var start = n[0] | + | |
- | var end = n[-1] | + | |
- | --- | + | |
- | end - start | + | |
- | } | + | |
- | + | ||
- | --- | + | |
- | diff([1990, 1995, 2002, 2008, 2021]) | + | |
- | </ | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
- | input payload application/ | ||
- | var user = {" | ||
- | var foo = " | ||
- | fun getName(data) = (data.firstName ++ ' ' ++ data.lastName) | ||
- | var toFullname = (data) -> (data.firstName ++ ' ' ++ data.lastName) | ||
--- | --- | ||
- | { | + | {"a":" |
- | "foo" : foo, | + | |
- | "getName" : getName(user), | + | |
- | "toFullname" : toFullname(user) | + | |
- | } | + | |
</ | </ | ||
- | |||
- | ==== $, $$, $$$ Syntax ==== | ||
- | |||
- | HOF настолько распространены в библиотеке DataWeave, что существуют дополнительные синтаксические функции, | ||
- | |||
- | * **$** Представляет текущее значение объекта. | ||
- | * **$$** | ||
- | * **$$$** | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
- | |||
- | var numbers = (1 to 5) | ||
--- | --- | ||
- | numbers filter | + | payload mapObject |
- | </ | + | |
- | + | } | |
- | < | + | |
- | %dw 2.0 | + | |
- | output json | + | |
- | --- | + | |
- | payload filter $.price > 5 | + | |
</ | </ | ||
Строка 1088: | Строка 816: | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
+ | var user = {" | ||
+ | var userList = [{" | ||
+ | {" | ||
+ | ] | ||
--- | --- | ||
{ | { | ||
- | user: | + | mapObject: |
- | + | '$key-$index': | |
- | user: null mapObject | + | |
- | ' | + | |
}, | }, | ||
- | users : null map ((value, index) -> value.firstName) | + | pluck: user pluck (value, key, index) -> (key ++ ' |
- | } | + | |
- | </ | + | |
- | ===== Pattern Matching ===== | + | filter: user filterObject ((value, key, index) -> (index < 1)), |
+ | filter2: userList filter ((value, index) -> (index < 1)), | ||
- | Выражение соответствия содержит список операторов case , которые при необходимости могут содержать оператор else . Каждый оператор case состоит из выражения условного селектора, которое должно иметь значение true или false . | + | groupBy1 : user groupBy (value, key) -> key endsWith ' |
- | Сопоставление с образцом — это еще один метод управления потоком, | + | groupBy2 : userList groupBy ((value, index) -> value.lastName) |
- | < | ||
- | %dw 2.0 | ||
- | output json | ||
- | --- | ||
- | payload.action match { | ||
- | case " | ||
- | case " | ||
- | case " | ||
- | else -> " | ||
} | } | ||
</ | </ | ||
- | < | + | === pluck === |
- | %dw 1.0 | + | |
- | input payload application/ | + | |
- | output application/ | + | |
- | var data = " | + | |
- | --- | + | |
- | data scan /\w++, \w++|\w++/ reduce ($$ ++ $) | + | |
- | </ | + | |
- | ===== Управление потоком / Flow Control ===== | + | |
- | + | ||
- | * do | + | |
- | * if else | + | |
- | * else if | + | |
- | + | это функция, | |
- | ==== do statement in flow ==== | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output json |
- | fun myfun() = do { | + | |
- | var name = " | + | |
- | --- | + | |
- | name | + | |
- | } | + | |
--- | --- | ||
- | { result: myfun() } | + | payload pluck (v,k,idx) -> {(k): v} |
</ | </ | ||
Строка 1149: | Строка 851: | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
- | var myVar = do { | + | var requestBody= |
- | | + | { |
- | | + | |
- | name | + | |
+ | | ||
} | } | ||
--- | --- | ||
- | { result: myVar } | + | { |
- | </ | + | value: requestBody pluck $, |
- | + | | |
- | + | | |
- | + | ||
- | < | + | |
- | %dw 2.0 | + | |
- | output application/ | + | |
- | fun test(p: String) = do { | + | |
- | | + | |
- | | + | |
- | a | + | |
} | } | ||
- | --- | ||
- | { result: test(" Bar") } | ||
</ | </ | ||
- | |||
< | < | ||
- | |||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
- | fun myfun() = do { | + | var requestBody= |
- | var msg = "Hello World!" | + | |
- | --- | + | |
- | msg | + | |
- | } | + | |
- | fun sayhi(s: String) = do { | + | |
- | var msg = "Hello " ++ s ++ " | + | |
- | --- | + | |
- | msg | + | |
- | } | + | |
- | --- | + | |
{ | { | ||
- | result: myfun(), | + | " |
- | result: sayhi("Jimmy") | + | { |
+ | " | ||
+ | " | ||
+ | | ||
+ | " | ||
+ | }, | ||
+ | " | ||
+ | { | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | }, | ||
+ | " | ||
+ | { | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | }, | ||
+ | " | ||
+ | { | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | } | ||
} | } | ||
- | </ | ||
- | ==== Операторы условия / if else Condition in flow ==== | ||
- | |||
- | < | ||
- | %dw 2.0 | ||
- | var myVar = { country : " | ||
- | output application/ | ||
--- | --- | ||
- | if (myVar.country | + | car: |
- | { currency: " | + | |
- | else { currency: "EUR" | + | |
</ | </ | ||
+ | === reduce === | ||
- | ==== Операторы условия | + | Функция уменьшения используется для выполнения любых вычислений во время итерации массива, |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output json |
--- | --- | ||
- | [" | + | payload reduce (n, total) -> total + n |
- | var hello = if(country == " | + | |
- | else if(country == " | + | |
- | else if(country == " | + | |
- | else " | + | |
- | --- | + | |
- | " | + | |
- | } | + | |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myVar = { country : " | ||
output application/ | output application/ | ||
--- | --- | ||
- | if (myVar.country == " | + | [2, 3] reduce |
- | { currency: " | + | |
- | else { currency: " | + | |
- | </ | + | |
- | < | + | Here |
- | %dw 2.0 | + | |
- | var aRecord = | + | |
- | [ | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | ] | + | |
- | output application/ | + | |
- | --- | + | |
- | { examples: | + | |
- | { | + | |
- | ex1 : if (1 + 1 == 55) true | + | |
- | else false, | + | |
- | ex2 : if ([1, | + | |
- | else "value of index 1 is not 1", | + | |
- | ex3 : if (isEmpty(aRecord.bookId)) "ID is empty" | + | |
- | else "ID is not empty", | + | |
- | ex4 : aRecord.bookId map (idValue) -> | + | |
- | if (idValue as Number == 101) idValue as Number | + | |
- | else "not 101" | + | |
- | } | + | |
- | } | + | |
- | </ | + | |
- | ===== Логические операторы / Logical Operators ===== | + | [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) | ||
+ | Acc = ($=3 + $$=2) = 5 | ||
- | * A > B Greater than | + | So result |
- | * A < B Less than | + | |
- | * A >= B Greater than or equal to | + | |
- | * A <= B Less than or equal to | + | |
- | * A == B Equal to | + | |
- | * A != B Not equal to | + | |
- | * A ~= B Similar to | + | |
- | * not A Logical negation | + | |
- | * !A Logical negation | + | |
- | * A and B Logical and | + | |
- | * A or B Logical or | + | |
- | * not Negates the result | + | |
- | * ! Negates the result of the input. See also, not. Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later. | + | |
- | * and Returns true if the result of all inputs is true, false if not. | + | |
- | * or Returns true if the result of any input is true, false if not. | + | |
- | + | ||
- | < | + | |
- | %dw 2.0 | + | |
- | output json | + | |
- | var age = 2 | + | |
- | --- | + | |
- | age < 10 | + | |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myArray = [1,2,3,4,5] | ||
- | var myMap = myArray map not (($ mod 2) == 0) | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | [2,3] reduce |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | ], | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | ], | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | ] | + | |
- | } | + | |
- | </ | + | |
- | < | + | Here |
- | %dw 2.0 | + | |
- | var orNot = if (1 + 1 == 4 or not 1 == 2) {" | + | |
- | else {" | + | |
- | var andNot = if (1 + 1 == 2 and not 1 == 2) {" | + | |
- | else {" | + | |
- | var notWithAndNot = if (not (1 + 1 == 2 and not 1 == 1)) {" | + | |
- | else {" | + | |
- | output application/ | + | |
- | --- | + | |
- | { " | + | |
- | [ | + | |
- | orNot, | + | |
- | andNot, | + | |
- | notWithAndNot | + | |
- | ] | + | |
- | } | + | |
- | </ | + | |
- | ===== Получение данных ===== | + | [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) | ||
+ | Acc = acc + item -> 4 + 2 -> 6 | ||
+ | Acc = acc + item -> 6 + 3 -> 9 | ||
- | * Single-value selector: . | + | So result will be 9 |
- | * Index selector: [n] | + | </ |
- | * Range selector: [n to m] | + | |
- | * Multi-value selector: .* | + | |
- | * Descendants selector: .. | + | |
- | * XML Attribute Selector (.@myKey) | + | |
- | * Namespace Selector (#) | + | |
- | * Selector Modifiers (!, ?) | + | |
- | * Filter Selectors (myKey[?($ == “aValue”)]) | + | |
- | * Metadata Selector (.^someMetadata) | + | |
- | + | ||
- | ==== Raw Metadata Selector (.^raw) ==== | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | import * from dw::Crypto | ||
output application/ | output application/ | ||
- | --- | ||
- | { “myRawData” : MD5(payload.^raw) } | ||
- | </ | ||
- | < | + | var data = {" |
- | %dw 2.0 | + | |
- | output application/ | + | |
--- | --- | ||
- | ((payload.^raw as String) scan / | + | data..value reduce $ |
</ | </ | ||
- | ==== Raw Metadata Selector (.^customMetadataValue) ==== | + | === read === |
- | < | + | * **stringToParse** The string or binary to read. |
- | %dw 2.0 | + | * **contentType** A supported format (or content type). Default: |
- | output | + | |
- | var userName = “DataWeave” as String {myCustomMetadata: | + | |
- | --- | + | |
- | { | + | |
- | | + | |
- | “valueOfVariable” : userName, | + | |
- | } | + | |
- | </ | + | |
- | + | ||
- | ==== Filter Selectors (myKey[?($ == “aValue”)]) ==== | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
+ | var inputData= | ||
+ | " | ||
+ | Joseph, | ||
+ | James, | ||
--- | --- | ||
- | { users: payload.users.*name[? | + | read(inputData," |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | var myVar = "Some, Body" | ||
output application/ | output application/ | ||
--- | --- | ||
- | { users: payload.users.*name[? | + | read(myVar," |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output application/ | + | output application/ |
--- | --- | ||
- | payload mapObject | + | read('{ " |
</ | </ | ||
- | ==== Selector Modifiers (!, ?) ==== | + | === readUrl |
- | * ! оценивает выбор и завершается с ошибкой с сообщением об исключении, если ключ отсутствует. | + | * **url** The URL string to read. It also accepts a classpath-based URL. for example: classpath: |
- | * ? возвращает true, если выбранный ключ присутствует, | + | * **contentType** A supported format (or MIME type). Default: application/ |
+ | * **readerProperties** Optional: | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output application/ | + | output application/ |
--- | --- | ||
- | present: payload.name? | + | readUrl(" |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | var myJsonSnippet = readUrl(" |
+ | output application/ | ||
--- | --- | ||
- | { | + | (myJsonSnippet.results map(item) -> item.profile) |
- | item: { | + | |
- | typePresent : payload.product.@.”type”? | + | |
- | } | + | |
- | } | + | |
</ | </ | ||
- | |||
- | ==== Namespace Selector (#) ==== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output |
--- | --- | ||
- | payload.order.# | + | readUrl(" |
</ | </ | ||
- | |||
- | ==== XML Attribute Selector (.@myKey) ==== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myVar = read(‘< | ||
- | < | ||
- | </ | ||
output application/ | output application/ | ||
+ | var inputData=readUrl(" | ||
--- | --- | ||
{ | { | ||
- | item: [ | + | name: inputData.name, |
- | { | + | |
- | “type” : myVar.product.@.”type”, | + | email: inputData.email |
- | | + | |
- | | + | |
- | } | + | |
- | ] | + | |
} | } | ||
</ | </ | ||
+ | === splitBy === | ||
- | ==== Range selector (anIndex to anotherIndex) ==== | + | Разбивает строку на массив строк на основе входного значения или соответствует части этой входной строки. Он отфильтровывает соответствующую часть из возвращаемого массива. Строка или регулярное выражение Java, используемое для разделения строки. Если какая-то часть строки не соответствует, |
- | Если вам нужно несколько последовательных значений из массива, DataWeave позволяет | + | Эта версия splitBy принимает регулярное |
- | < | + | * **text** The input string to split. |
- | %dw 2.0 | + | * **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. |
- | output json | + | |
- | -- | + | |
- | payload[0 | + | |
- | </ | + | |
< | < | ||
Строка 1463: | Строка 1041: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | { " |
- | slice: [0,1,2][0 to 1], | + | " |
- | last: [0,1,2][-1 to 0] | + | " |
+ | " | ||
+ | " | ||
+ | " | ||
+ | } | ||
} | } | ||
</ | </ | ||
Строка 1473: | Строка 1055: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | { " |
- | slice: “DataWeave”[0 to 1], | + | " |
- | | + | " |
- | last: “DataWeave”[-1 to 0] | + | " |
+ | " | ||
+ | } | ||
} | } | ||
</ | </ | ||
- | ==== Index Selector ([]) ==== | + | === valuesOf |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output json | + | output |
--- | --- | ||
- | payload[1] | + | valuesOf(payload.responses) filter ($.fieldname ~= " |
</ | </ | ||
- | |||
- | ==== Key-Value Pair Selector (.& | ||
- | |||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output application/ | + | output application/ |
--- | --- | ||
- | { | + | payload |
- | users: | + | |
- | } | + | |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | + | output application/ | |
- | var myData = { | + | |
- | “people”: | + | |
- | “person”: | + | |
- | “name”: “Nial”, | + | |
- | “address”: | + | |
- | “street”: | + | |
- | “name”: “Italia”, | + | |
- | “number”: | + | |
- | }, | + | |
- | “area”: { | + | |
- | “zone”: “San Isidro”, | + | |
- | “name”: “Martinez” | + | |
- | } | + | |
- | } | + | |
- | } | + | |
- | } | + | |
- | } | + | |
- | output application/ | + | |
--- | --- | ||
- | names: {(myData.people..& | + | payload splitBy(/s/) |
</ | </ | ||
- | |||
- | ==== Descendants Selector (..) ==== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output json | + | output |
--- | --- | ||
- | payload..echo | + | "192.88.99.0/ |
</ | </ | ||
Строка 1538: | Строка 1097: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { names: payload.people..name } | + | "192.88.99.0" splitBy(" |
</ | </ | ||
- | ==== Multi-Value Selector (.*) ==== | + | ==== Working with Objects / dw:: |
- | < | + | * **divideBy** Breaks up an object into sub-objects that contain the specified number of key-value pairs. |
- | %dw 2.0 | + | * **entrySet** Returns an array of key-value pairs that describe the key, value, and any attributes in the input object. |
- | output json | + | * **everyEntry** Returns true if every entry in the object matches the condition. |
- | --- | + | * **keySet** Returns an array of key names from an object. |
- | payload.*name | + | * **mergeWith** Appends any key-value pairs from a source object to a target object. |
- | </ | + | * **nameSet** Returns an array of keys from an object. |
+ | | ||
+ | * **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. | ||
+ | |||
+ | === everyEntry === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | + | import everyEntry from dw::core::Objects | |
- | var myArrayOfKeyValuePairs = [ “aString”: “hello”, | + | |
- | var myArrayOfObjects = [ { “aString”: “hello” }, { “aNum”: 2 }, { “aString” : “world” } ] | + | |
output application/ | output application/ | ||
--- | --- | ||
{ | { | ||
- | | + | |
- | | + | |
+ | c: {a: "", | ||
+ | d: {a: "", | ||
+ | e: {a: "" | ||
+ | f: null everyEntry ((value, key) -> key as String == " | ||
} | } | ||
</ | </ | ||
- | ==== Single-Value Selector ==== | + | === mergeWith |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | + | import mergeWith from dw:: | |
- | output json | + | output |
--- | --- | ||
- | payload.age | + | { " |
</ | </ | ||
+ | |||
+ | === someEntry === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | + | import someEntry from dw:: | |
- | output json | + | output |
--- | --- | ||
{ | { | ||
- | fixed: payload.age, | + | a: {} someEntry (value, key) -> value is String, |
- | | + | b: {a: "", |
+ | c: {a: "", | ||
+ | d: {a: "", | ||
+ | e: {a: "" | ||
+ | f: null someEntry (value, key) -> key as String == " | ||
} | } | ||
</ | </ | ||
+ | ==== dw:: | ||
- | < | + | === Selector Expressions (update Operator) === |
- | %dw 2.0 | + | |
- | var myObject = { user : “a” } | + | update оператор позволяет обновлять указанные поля структуры данных новыми значениями. |
- | output application/ | + | Этот селектор соответствия может проверять совпадения с любым значением внутри объекта. |
- | --- | + | |
- | { myObjectExample : myObject.user } | + | |
- | </ | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | + | var myInput | |
- | var myData | + | " |
- | | + | |
- | | + | |
- | | + | " |
- | “name”: “Nial”, | + | |
- | “address”: { | + | |
- | | + | |
- | “name”: “Italia”, | + | |
- | “number”: | + | |
- | | + | |
- | “area”: { | + | |
- | “zone”: “San Isidro”, | + | |
- | “name”: “Martinez” | + | |
- | } | + | |
- | } | + | |
} | } | ||
- | } | ||
} | } | ||
- | output application/ | + | output application/ |
--- | --- | ||
- | { myaddresses: | + | myInput update |
+ | case age at .age -> age + 1 | ||
+ | case s at .address.street -> "First Street" | ||
+ | } | ||
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | |||
- | var myArrayOfKeyValuePairs = [ “aString”: | ||
- | var myArrayOfObjects = [ { “aString”: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | payload update |
- | | + | |
- | | + | " |
+ | " | ||
+ | } | ||
} | } | ||
</ | </ | ||
- | |||
- | ===== Типы данных ===== | ||
- | |||
- | * Number / Numbers (dw:: | ||
- | * String / Strings (dw:: | ||
- | * Boolean / Boolean (dw::Core Type) | ||
- | * Array / Arrays (dw:: | ||
- | * Object / Object (dw::Core Type) или {} | ||
< | < | ||
Строка 1644: | Строка 1197: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | payload update |
- | /* | + | case name at .user.@name -> upper(name) |
- | * A multi-line | + | |
- | * comment here. | + | |
- | */ | + | |
- | myString: "hello world", | + | |
- | myNumber: 123, | + | |
- | myFloatingPointNumber: | + | |
- | myVeryBigNumber: | + | |
- | myDate: |2018-12-07|, | + | |
- | myTime: |11: | + | |
- | myDateTime: |2018-10-01T23: | + | |
- | myBoolean: true, | + | |
- | myArray: [ 1, 2, 3, 5, 8], | + | |
- | myMixedArray: | + | |
- | myObjectKeyValuePair: | + | |
- | myObjectWithConditionalField: | + | |
- | myNull: null, | + | |
- | myBinary: " | + | |
- | //A one-line comment here. | + | |
} | } | ||
</ | </ | ||
Строка 1669: | Строка 1204: | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | + | var theFieldName = " | |
- | output json | + | output |
--- | --- | ||
- | typeOf({}) | + | payload update |
+ | case s at ." | ||
+ | } | ||
</ | </ | ||
- | |||
- | ===== Конвертирование массива в строку / join ===== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var payload = [1,2,3,4,5] | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | payload map ((user) -> |
- | "a": payload joinBy | + | |
- | } | + | case name at .name if(name == "Ken") -> name ++ " (Leandro)" |
+ | case name at .name if(name == " | ||
+ | } | ||
+ | ) | ||
</ | </ | ||
- | |||
- | ===== Конвертирование строки в массив / split ===== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var payload | + | var myInput |
- | output application/ | + | output application/ |
--- | --- | ||
- | payload splitBy(" ") | + | myInput |
+ | value update { | ||
+ | case name at .name! -> if(name == null) "JOHN" | ||
+ | } | ||
+ | ) | ||
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var payload = “a.b.c” | + | output application/ |
- | output application/ | + | |
--- | --- | ||
- | payload | + | payload |
+ | // | ||
+ | //case age at .age -> age + 1 | ||
+ | case .age -> $ + 1 | ||
+ | case .address.street -> "First Street" | ||
+ | } | ||
</ | </ | ||
- | |||
- | ===== Итерация фиксированного количества циклов ===== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var payload | + | var myInput |
- | " | + | " |
- | " | + | "lastName":" |
- | | + | " |
- | { | + | |
- | | + | |
- | "age":34 | + | |
- | }, | + | |
- | { | + | |
- | | + | |
- | " | + | |
- | }, | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | }, | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | }, | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | }, | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | } | + | |
- | ] | + | |
} | } | ||
output application/ | output application/ | ||
--- | --- | ||
- | (payload.employees | + | myInput mapObject |
- | FirstName: $.name, | + | |
- | age: $.age | + | |
- | })) [ 0 to payload.totalcount -3 ] | + | |
+ | | ||
</ | </ | ||
- | |||
- | ===== Преобразование JSON в CSV ===== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output application/ | + | var myInput = { |
+ | " | ||
+ | " | ||
+ | " | ||
+ | } | ||
+ | output application/ | ||
--- | --- | ||
- | payload | + | myInput update { |
+ | case age at .age -> age + 1 | ||
+ | } | ||
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output application/ | + | output application/ |
--- | --- | ||
- | payload | + | payload |
+ | item.ServiceDetails update { | ||
+ | case Designation at .Designation if (Designation == " | ||
+ | }) | ||
</ | </ | ||
- | |||
- | < | ||
- | %dw 2.0 | ||
- | output application/ | ||
- | --- | ||
- | payload | ||
- | </ | ||
- | |||
- | ===== Заголовок ===== | ||
- | |||
====== Ссылки ====== | ====== Ссылки ====== | ||
* https:// | * https:// | ||
+ | * https:// | ||
+ | * https:// | ||
+ | * https:// |