Различия
Показаны различия между двумя версиями страницы.
Предыдущая версия справа и слева Предыдущая версия Следующая версия | Предыдущая версия | ||
develop:mule:dataweave [2024/02/13 23:44] – 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, |
</ | </ | ||
- | |||
- | ===== pluck ===== | ||
- | |||
- | это функция, | ||
< | < | ||
Строка 215: | Строка 146: | ||
output json | output json | ||
--- | --- | ||
- | payload pluck (v,k,idx) -> {(k): v} | + | (() -> 2 + 3)() |
</ | </ | ||
Строка 221: | Строка 152: | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
- | var requestBody= | + | var toUser |
- | { | + | |
- | " | + | |
- | " | + | |
- | " | + | |
} | } | ||
--- | --- | ||
{ | { | ||
- | value: requestBody pluck $, | + | " |
- | keys: requestBody pluck $$, | + | |
- | indexes: requestBody pluck $$$ | + | |
} | } | ||
</ | </ | ||
- | < | + | === Логические операторы |
- | %dw 2.0 | + | |
- | output application/ | + | |
- | var requestBody= | + | |
- | { | + | |
- | " | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | }, | + | |
- | " | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | }, | + | |
- | " | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | }, | + | |
- | " | + | |
- | { | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | } | + | |
- | } | + | |
- | --- | + | |
- | car: | + | |
- | </code> | + | |
- | ===== Selector Expressions (update Operator) ===== | + | * A > B Greater than |
- | + | * A < B Less than | |
- | update оператор позволяет обновлять указанные поля структуры данных новыми значениями. | + | * 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 | ||
- | var myInput | + | output json |
- | " | + | var age = 2 |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | " | + | |
- | } | + | |
- | } | + | |
- | output application/ | + | |
--- | --- | ||
- | myInput update { | + | age < 10 |
- | case age at .age -> age + 1 | + | |
- | case s at .address.street -> "First Street" | + | |
- | } | + | |
</ | </ | ||
< | < | ||
%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/ | ||
--- | --- | ||
- | payload update | + | { |
- | case s at .addresses[0] -> { | + | " |
- | "street": "Second Street", | + | " |
- | "zipCode": "ZZ123" | + | " |
- | | + | " |
+ | | ||
+ | "and" : [ | ||
+ | | ||
+ | "andIsTrue" : (1 + 1 == 2) and (2 + 2 == 4), | ||
+ | | ||
+ | ], | ||
+ | " | ||
+ | | ||
+ | " | ||
+ | " | ||
+ | ], | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | ] | ||
} | } | ||
</ | </ | ||
Строка 311: | Строка 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/ | ||
--- | --- | ||
- | payload update | + | { " |
- | | + | [ |
+ | | ||
+ | andNot, | ||
+ | notWithAndNot | ||
+ | ] | ||
} | } | ||
</ | </ | ||
+ | |||
+ | === Types === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var theFieldName = " | ||
output application/ | output application/ | ||
--- | --- | ||
- | payload update | + | { |
- | case s at ."$(theFieldName)" -> "Shoki" | + | /* |
+ | * A multi-line | ||
+ | * comment here. | ||
+ | */ | ||
+ | myString: | ||
+ | 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::* ===== | ||
+ | |||
+ | ==== 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. | ||
+ | |||
+ | === divideBy === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | import divideBy from dw:: | ||
output application/ | output application/ | ||
--- | --- | ||
- | payload map ((user) -> | + | { "a": 1, "b": true, "a": 2, "b": false, " |
- | user update | + | |
- | case name at .name if(name == "Ken") -> name ++ " | + | |
- | case name at .name if(name == "Tomo") -> name ++ " | + | |
- | | + | |
- | ) | + | |
</ | </ | ||
+ | === drop === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myInput | + | import * from dw:: |
+ | var samplearray | ||
output application/ | output application/ | ||
--- | --- | ||
- | myInput | + | |
- | value update { | + | drop(samplearray, |
- | case name at .name! -> if(name == null) " | + | |
- | } | + | |
- | ) | + | |
</ | </ | ||
+ | |||
+ | === indexOf === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | import * from dw:: | ||
+ | var samplearray = [" | ||
output application/ | output application/ | ||
--- | --- | ||
- | payload update { | + | |
- | // | + | indexOf(samplearray, |
- | //case age at .age -> age + 1 | + | |
- | case .age -> $ + 1 | + | |
- | case .address.street -> "First Street" | + | |
- | } | + | |
</ | </ | ||
+ | |||
+ | === join === | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myInput | + | import * from dw:: |
- | | + | |
- | | + | var items = [{id: "12", |
- | | + | |
- | } | + | var Prices = [{Id: " |
+ | |||
output application/ | output application/ | ||
--- | --- | ||
- | myInput mapObject | + | join(items, Prices, |
- | if(key as String == " | + | |
- | {(key): value as Number + 1} | + | |
- | | + | |
- | | + | |
</ | </ | ||
+ | === takeWhile === | ||
+ | |||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myInput = { | + | import * from dw::core::Arrays |
- | " | + | |
- | " | + | |
- | " | + | |
- | } | + | |
output application/ | output application/ | ||
+ | var arr = [1, | ||
--- | --- | ||
- | myInput update { | + | |
- | case age at .age -> age + 1 | + | arr takeWhile $ <= 2 |
- | } | + | |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | import * from dw:: | ||
output application/ | output application/ | ||
+ | var obj = { | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | } | ||
--- | --- | ||
- | 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 |
</ | </ | ||
Строка 420: | Строка 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. | + | |
< | < | ||
Строка 441: | Строка 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/ | + | |
- | --- | + | |
- | " | + | |
</ | </ | ||
Строка 489: | Строка 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: | ||
< | < | ||
Строка 534: | Строка 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 | + | |
Оператор | Оператор | ||
Строка 663: | Строка 534: | ||
Prefix Notation | Prefix Notation | ||
< | < | ||
- | filterOject({ }, (value, index) -> (condition)) | + | filterObject({ }, (value, index) -> (condition)) |
</ | </ | ||
Строка 745: | Строка 616: | ||
--- | --- | ||
payload | payload | ||
- | filterO | + | filterObject |
- | bject | + | |
$ is Array | $ is Array | ||
</ | </ | ||
Строка 782: | Строка 652: | ||
</ | </ | ||
- | ==== Filter Arrays ==== | ||
- | |||
- | Infix Notation: Long-Hand | ||
< | < | ||
- | [ ] filter | + | %dw 2.0 |
+ | output application/ | ||
+ | --- | ||
+ | payload filterObject ((value, | ||
+ | | ||
+ | and (key as String != "last name" | ||
+ | ) | ||
</ | </ | ||
+ | === flatten === | ||
- | Infix Notation: $ syntax | + | Для перемещения элементов из подмассивов в родительский массив, удаления подмассивов и преобразования всех пар ключ-значение в список объектов в родительском массиве. С помощью функции Flatten несколько массивов объединяются в один массив. |
- | < | + | |
- | [ ] filter (< | + | |
- | </ | + | |
- | Prefix Notation | + | * **items** The input array of arrays made up of any supported types. |
- | < | + | |
- | filter([ ], (value, index) -> (condition)) | + | |
- | </ | + | |
- | + | ||
- | Filter Expression | + | |
- | < | + | |
- | [ ] [? (< | + | |
- | </ | + | |
< | < | ||
Строка 808: | Строка 671: | ||
output application/ | output application/ | ||
--- | --- | ||
- | [" | + | flatten(payload) |
- | filter | + | |
- | (value) -> (value contains " | + | |
</ | </ | ||
Строка 816: | Строка 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 принимает список объектов [x1,…,xn] и некоторую функцию f. Затем она отображает f в списке, | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output json |
--- | --- | ||
- | [" | + | payload groupBy (n, idx) -> isEven(n) |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output json |
--- | --- | ||
- | payload | + | payload |
- | filter | + | |
- | (value, index) -> ((value.cik_str mod 2) == 1) and | + | |
- | (index > 5) and | + | |
- | (value.ticker startsWith | + | |
</ | </ | ||
Строка 843: | Строка 705: | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
+ | var user = {" | ||
--- | --- | ||
- | [" | + | user groupBy ((value, key) -> if (key contains ' |
</ | </ | ||
- | ===== Functions ===== | ||
- | * Named functions | + | === map === |
- | * 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 |
- | + | ||
- | var numbers = (1 to 5) | + | |
--- | --- | ||
- | numbers filter | + | { |
+ | " | ||
+ | " | ||
+ | }) | ||
+ | } | ||
</ | </ | ||
Строка 874: | Строка 730: | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
- | |||
- | var numbers = (1 to 5) | ||
--- | --- | ||
- | numbers | + | payload map (n, idx) -> n + 1 |
- | filter ((n, idx) -> (n mod 2) == 1) | + | |
- | filter ((n, idx) -> (n > 3)) | + | |
</ | </ | ||
Строка 886: | Строка 738: | ||
output json | output json | ||
--- | --- | ||
- | [ ] filter | + | payload.items.*name map ( |
+ | (item, index) -> {name: item} | ||
+ | ) | ||
</ | </ | ||
< | < | ||
+ | |||
%dw 2.0 | %dw 2.0 | ||
- | output json | + | 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 | ||
--- | --- | ||
- | [ ] filter | + | myVar map (item, index) -> using (id = item.bookId) { |
+ | " | ||
+ | " | ||
+ | " | ||
+ | (myVar2 filter ($.*bookId contains id) map (item) -> { | ||
+ | author : item.author | ||
+ | }) | ||
+ | } | ||
</ | </ | ||
- | |||
- | ==== Prefix Notation | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | output |
+ | fun process(obj: | ||
+ | (key): key match { | ||
+ | case " | ||
+ | else -> value | ||
+ | } | ||
+ | }) | ||
--- | --- | ||
- | filter([ ], (value, index) -> (condition)) | + | payload map ((item, index) -> |
+ | process(item) | ||
+ | ) | ||
</ | </ | ||
+ | === mapObject === | ||
- | ==== Лямда функции | + | Функция mapObject |
- | + | ||
- | Полезность лямбд становится очевидной, | + | |
- | + | ||
- | * Лямбды — это значения, такие же, как строки, | + | |
- | * Значения могут передаваться функциям в качестве аргументов, а также возвращаться из функций. | + | |
- | + | ||
- | В DataWeave функции и лямбды (анонимные функции) могут | + | |
- | + | ||
- | DataWeave | + | |
- | + | ||
- | <note tip> | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output json | + | output |
- | + | ||
- | fun isOddNum(n) = | + | |
- | (n mod 2) == 1 | + | |
- | + | ||
- | // Generate [1, 2, ..., 5] | + | |
- | var numbers = (1 to 5) | + | |
--- | --- | ||
- | filter(numbers, (n, idx) -> isOddNum(n)) | + | {" |
</ | </ | ||
Строка 934: | Строка 807: | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
- | |||
- | var numbers = (1 to 5) | ||
--- | --- | ||
- | filter(numbers, (n, idx) -> (n mod 2) == 1) | + | payload mapObject |
- | </ | + | (upper(key)): value |
- | + | } | |
- | < | + | |
- | %dw 2.0 | + | |
- | output json | + | |
- | --- | + | |
- | (() -> 2 + 3)() | + | |
</ | </ | ||
Строка 950: | Строка 816: | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
- | var toUser = (user) -> { | + | var user = {"firstName": " |
- | | + | var userList = [{" |
- | lastName: | + | {" |
- | } | + | ] |
--- | --- | ||
{ | { | ||
- | "user" | + | mapObject: |
+ | ' | ||
+ | }, | ||
+ | |||
+ | pluck: user pluck (value, key, index) -> (key ++ ' | ||
+ | |||
+ | filter: user filterObject ((value, key, index) -> (index < 1)), | ||
+ | filter2: userList filter ((value, index) -> (index < 1)), | ||
+ | |||
+ | groupBy1 : user groupBy (value, key) -> key endsWith ' | ||
+ | groupBy2 : userList groupBy ((value, index) -> value.lastName) | ||
} | } | ||
</ | </ | ||
- | ==== Именованные функции / Named Functions ==== | + | === pluck === |
- | Для создания | + | это функция, используемая для преобразования свойств и значений этих свойств объекта в массив свойств, массив значений и массив индексов этих свойств. Эту функцию можно использовать, если вам нужно преобразовать объект в массив. |
- | + | ||
- | <note tip> | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
- | |||
- | fun add(n, m) = | ||
- | n + m | ||
--- | --- | ||
- | add(1,2) | + | payload pluck (v,k,idx) -> {(k): v} |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output json | + | output |
- | + | var requestBody= | |
- | fun diff(n) = do { | + | { |
- | var start = n[0] | + | " |
- | var end = n[-1] | + | " |
- | --- | + | " |
- | end - start | + | |
} | } | ||
- | |||
--- | --- | ||
- | diff([1990, 1995, 2002, 2008, 2021]) | + | { |
+ | value: requestBody pluck $, | ||
+ | keys: requestBody pluck $$, | ||
+ | indexes: requestBody pluck $$$ | ||
+ | } | ||
</ | </ | ||
Строка 994: | Строка 868: | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
- | input payload application/ | + | var requestBody= |
- | var user = {" | + | |
- | var foo = " | + | |
- | fun getName(data) = (data.firstName ++ ' ' ++ data.lastName) | + | |
- | var toFullname = (data) -> (data.firstName ++ ' ' ++ data.lastName) | + | |
- | --- | + | |
{ | { | ||
- | "foo" : foo, | + | |
- | "getName" : getName(user), | + | { |
- | "toFullname" : toFullname(user) | + | " |
+ | "MakeYear": | ||
+ | "Color": | ||
+ | " | ||
+ | }, | ||
+ | " | ||
+ | { | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | }, | ||
+ | " | ||
+ | { | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | }, | ||
+ | " | ||
+ | { | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | } | ||
} | } | ||
+ | --- | ||
+ | car: | ||
</ | </ | ||
+ | === reduce === | ||
- | ==== $, $$, $$$ Syntax ==== | + | Функция уменьшения используется для |
- | + | ||
- | HOF настолько распространены в библиотеке DataWeave, что существуют дополнительные синтаксические функции, | + | |
- | + | ||
- | * **$** Представляет | + | |
- | * **$$** | + | |
- | * **$$$** | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output json | output json | ||
- | |||
- | var numbers = (1 to 5) | ||
--- | --- | ||
- | numbers filter | + | payload reduce |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output json | + | output |
--- | --- | ||
- | payload filter | + | [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 | ||
</ | </ | ||
Строка 1035: | Строка 934: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | [2,3] reduce |
- | user: null filter | + | |
- | user: null mapObject { | + | Here |
- | ' | + | |
- | }, | + | |
- | users : null map ((value, index) -> value.firstName) | + | [2,3] – is the input array |
- | } | + | acc will take the initialized value = 4 |
- | </code> | + | 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 | ||
- | ===== Pattern Matching ===== | + | So result will be 9 |
- | + | ||
- | Выражение соответствия содержит список операторов case , которые при необходимости могут содержать оператор else . Каждый оператор case состоит из выражения условного селектора, | + | |
- | Сопоставление с образцом — это еще один метод управления потоком, | + | |
- | + | ||
- | < | + | |
- | %dw 2.0 | + | |
- | output json | + | |
- | --- | + | |
- | payload.action match { | + | |
- | case " | + | |
- | case " | + | |
- | case " | + | |
- | else -> " | + | |
- | } | + | |
</ | </ | ||
< | < | ||
- | %dw 1.0 | + | %dw 2.0 |
- | input payload application/ | + | |
output application/ | output application/ | ||
- | var data = "Hello I am from \"StackOverflow, | + | |
+ | var data = {"xyz": {"abc": | ||
--- | --- | ||
- | data scan /\w++, \w++|\w++/ | + | data..value |
</ | </ | ||
- | ===== Управление потоком / Flow Control ===== | ||
- | * do | + | === read === |
- | * if else | + | |
- | * else if | + | |
- | + | * **stringToParse** The string or binary to read. | |
- | ==== do statement in flow ==== | + | * **contentType** A supported format (or content type). Default: application/ |
+ | * **readerProperties** Optional: | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
- | fun myfun() | + | var inputData= |
- | | + | "name,age,salary |
- | --- | + | Joseph, |
- | | + | James, |
- | } | + | |
--- | --- | ||
- | { result: myfun() } | + | read(inputData," |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | var myVar = "Some, Body" | ||
output application/ | output application/ | ||
- | var myVar = do { | ||
- | var name = " | ||
- | --- | ||
- | name | ||
- | } | ||
--- | --- | ||
- | { result: myVar } | + | read(myVar," |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output application/ | + | output application/ |
- | fun test(p: String) = do { | + | |
- | var a = " | + | |
- | --- | + | |
- | a | + | |
- | } | + | |
--- | --- | ||
- | { result: test(" | + | read('{ " |
</ | </ | ||
- | ==== Операторы условия / if else Condition in flow ==== | + | === 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: | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myVar = { country : " | ||
output application/ | output application/ | ||
--- | --- | ||
- | if (myVar.country == "USA" | + | readUrl("classpath:// |
- | { currency: "USD" | + | |
- | else { currency: | + | |
</ | </ | ||
- | |||
- | ==== Операторы условия | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | var myJsonSnippet = readUrl(" |
+ | output application/ | ||
--- | --- | ||
- | [" | + | (myJsonSnippet.results |
- | 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 == "UAE" | + | readUrl("https:// |
- | { currency: "EUR" | + | |
- | else { currency: | + | |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var aRecord | + | output application/ |
- | [ | + | var inputData=readUrl("https:// |
- | " | + | |
- | | + | |
- | " | + | |
- | ] | + | |
- | output | + | |
--- | --- | ||
- | { examples: | + | { |
- | | + | |
- | | + | |
- | else false, | + | email: inputData.email |
- | 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" | + | |
- | } | + | |
} | } | ||
</ | </ | ||
+ | === splitBy === | ||
- | ===== Логические операторы / Logical Operators ===== | + | Разбивает строку на массив строк на основе входного значения или соответствует |
- | * A > B Greater than | + | Эта версия splitBy принимает регулярное выражение Java (регулярное выражение), соответствующее входной строке. Регулярное выражение может соответствовать любому символу во входной строке. Обратите внимание, что splitBy выполняет противоположную операцию joinBy. |
- | * 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. | + | |
- | < | + | * **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 | + | |
- | 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/ | ||
--- | --- | ||
- | { | + | { "splitters" : { |
- | | + | |
- | "notTrue" : not true, | + | |
- | | + | |
- | "myMapWithNot" : myMap | + | |
- | ], | + | |
- | | + | |
- | " | + | |
- | "andIsTrue" : (1 + 1 == 2) and (2 + 2 == 4), | + | |
- | | + | |
- | ], | + | |
- | "or" : [ | + | |
- | | + | |
- | " | + | |
- | "orIsFalse" : (1 + 1 == 1) or (2 + 2 == 2) | + | |
- | ], | + | |
- | | + | |
- | " | + | |
- | " | + | |
- | | + | |
} | } | ||
</ | </ | ||
Строка 1236: | Строка 1053: | ||
< | < | ||
%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/ | ||
--- | --- | ||
- | { "answers" : | + | { "splitters" : { |
- | [ | + | " |
- | | + | |
- | | + | |
- | | + | |
- | ] | + | } |
} | } | ||
</ | </ | ||
- | ===== Получение данных ===== | + | === valuesOf |
- | + | ||
- | * Single-value selector: . | + | |
- | * 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) } | + | valuesOf(payload.responses) filter ($.fieldname ~= " |
</ | </ | ||
- | |||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
output application/ | output application/ | ||
--- | --- | ||
- | ((payload.^raw as String) scan / | + | payload |
</ | </ | ||
- | |||
- | ==== Raw Metadata Selector (.^customMetadataValue) ==== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output application/ | + | output application/ |
- | var userName = “DataWeave” as String {myCustomMetadata: | + | |
--- | --- | ||
- | { | + | payload splitBy(/ |
- | “valueOfVariableMetaData” : userName.^myCustomMetadata, | + | |
- | “valueOfVariable” : userName, | + | |
- | } | + | |
</ | </ | ||
- | |||
- | ==== Filter Selectors (myKey[?($ == “aValue”)]) ==== | ||
< | < | ||
Строка 1302: | Строка 1090: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { users: payload.users.*name[?($ == “Mariano”)] } | + | "192.88.99.0/ |
</ | </ | ||
Строка 1309: | Строка 1097: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { users: payload.users.*name[?( 1 == 1)] } | + | "192.88.99.0" splitBy(" |
</ | </ | ||
- | < | + | ==== Working with Objects |
- | %dw 2.0 | + | |
- | output application/json | + | |
- | --- | + | |
- | payload mapObject { ($$) : $[?($==”Mariano”)] } | + | |
- | </ | + | |
- | ==== Selector Modifiers (!, ?) ==== | + | * **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. | ||
- | * ! оценивает выбор и завершается с ошибкой с сообщением об исключении, | + | === everyEntry === |
- | * ? возвращает true, если выбранный ключ присутствует, | + | |
- | + | ||
- | < | + | |
- | %dw 2.0 | + | |
- | output application/ | + | |
- | --- | + | |
- | present: payload.name? | + | |
- | </ | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | import everyEntry from dw:: | ||
output application/ | output application/ | ||
--- | --- | ||
{ | { | ||
- | item: { | + | a: {} everyEntry (value, key) -> value is String, |
- | | + | |
- | } | + | c: {a: "", |
+ | d: {a: "", | ||
+ | e: {a: "" | ||
+ | f: null everyEntry ((value, key) -> key as String == " | ||
} | } | ||
</ | </ | ||
- | ==== Namespace Selector (#) ==== | + | === mergeWith |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output | + | import mergeWith from dw:: |
+ | output | ||
--- | --- | ||
- | payload.order.# | + | { " |
</ | </ | ||
- | ==== XML Attribute Selector (.@myKey) ==== | + | === someEntry |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | var myVar = read(‘< | + | import someEntry from dw:: |
- | < | + | |
- | </ | + | |
output application/ | output application/ | ||
--- | --- | ||
{ | { | ||
- | item: [ | + | a: {} someEntry (value, key) -> value is String, |
- | | + | b: {a: "", |
- | | + | c: {a: "", |
- | | + | d: {a: "", |
- | | + | |
- | } | + | f: null someEntry (value, key) -> key as String == " |
- | ] | + | |
} | } | ||
</ | </ | ||
+ | ==== dw:: | ||
- | ==== Range selector | + | === Selector Expressions |
- | Если вам нужно несколько последовательных значений из массива, DataWeave позволяет вам выбрать диапазон значений с помощью селектора диапазона (от [n до m]). | + | update |
- | + | Этот | |
- | < | + | |
- | %dw 2.0 | + | |
- | output json | + | |
- | -- | + | |
- | payload[0 to 1] | + | |
- | </ | + | |
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | var myInput = { | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | } | ||
+ | } | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | myInput update |
- | | + | case age at .age -> age + 1 |
- | last: [0,1,2][-1 to 0] | + | case s at .address.street |
} | } | ||
</ | </ | ||
Строка 1396: | Строка 1185: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | payload update |
- | | + | case s at .addresses[0] -> { |
- | | + | " |
- | last: “DataWeave”[-1 to 0] | + | " |
+ | } | ||
} | } | ||
</ | </ | ||
- | |||
- | ==== Index Selector ([]) ==== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output json | + | output |
--- | --- | ||
- | payload[1] | + | payload |
+ | case name at .user.@name -> upper(name) | ||
+ | } | ||
</ | </ | ||
- | |||
- | ==== Key-Value Pair Selector (.& | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output application/ | + | var theFieldName = " |
+ | output application/ | ||
--- | --- | ||
- | { | + | payload update |
- | | + | case s at ." |
} | } | ||
</ | </ | ||
Строка 1425: | Строка 1214: | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | + | output application/ | |
- | var myData = { | + | --- |
- | | + | payload map ((user) -> |
- | | + | |
- | “name”: “Nial”, | + | |
- | “address”: | + | |
- | “street”: | + | |
- | “name”: “Italia”, | + | |
- | “number”: | + | |
- | | + | |
- | “area”: { | + | |
- | “zone”: “San Isidro”, | + | |
- | “name”: “Martinez” | + | |
- | } | + | |
- | } | + | |
} | } | ||
- | } | + | ) |
- | } | + | |
- | output application/ | + | |
- | --- | + | |
- | names: {(myData.people..& | + | |
- | </ | + | |
- | + | ||
- | ==== Descendants Selector (..) ==== | + | |
- | + | ||
- | < | + | |
- | %dw 2.0 | + | |
- | output json | + | |
- | --- | + | |
- | payload..echo | + | |
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
+ | var myInput = [{" | ||
output application/ | output application/ | ||
--- | --- | ||
- | { names: payload.people..name } | + | myInput |
+ | value update | ||
+ | case name at .name! -> if(name == null) " | ||
+ | | ||
+ | ) | ||
</ | </ | ||
- | |||
- | ==== Multi-Value Selector (.*) ==== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | output json | ||
- | --- | ||
- | payload.*name | ||
- | </ | ||
- | |||
- | < | ||
- | %dw 2.0 | ||
- | |||
- | var myArrayOfKeyValuePairs = [ “aString”: | ||
- | var myArrayOfObjects = [ { “aString”: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | payload update |
- | | + | |
- | | + | //case age at .age -> age + 1 |
+ | | ||
+ | case .address.street -> "First Street" | ||
} | } | ||
</ | </ | ||
- | |||
- | ==== Single-Value Selector ==== | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | + | var myInput = { | |
- | output json | + | " |
- | --- | + | " |
- | payload.age | + | " |
- | </ | + | |
- | + | ||
- | < | + | |
- | %dw 2.0 | + | |
- | + | ||
- | output json | + | |
- | --- | + | |
- | { | + | |
- | fixed: payload.age, | + | |
- | | + | |
} | } | ||
- | </ | ||
- | |||
- | < | ||
- | %dw 2.0 | ||
- | |||
- | var myObject = { user : “a” } | ||
output application/ | output application/ | ||
--- | --- | ||
- | { myObjectExample | + | myInput mapObject ((value, |
+ | if(key as String == " | ||
+ | {(key): value as Number + 1} | ||
+ | else | ||
+ | | ||
</ | </ | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | + | var myInput | |
- | var myData | + | |
- | “people”: | + | |
- | | + | " |
- | | + | |
- | “name”: “Nial”, | + | |
- | | + | |
- | “street”: | + | |
- | “name”: “Italia”, | + | |
- | “number”: | + | |
- | }, | + | |
- | “area”: { | + | |
- | “zone”: “San Isidro”, | + | |
- | “name”: “Martinez” | + | |
- | } | + | |
- | } | + | |
- | } | + | |
- | } | + | |
} | } | ||
- | output application/ | ||
- | --- | ||
- | { myaddresses: | ||
- | </ | ||
- | |||
- | < | ||
- | %dw 2.0 | ||
- | |||
- | var myArrayOfKeyValuePairs = [ “aString”: | ||
- | var myArrayOfObjects = [ { “aString”: | ||
output application/ | output application/ | ||
--- | --- | ||
- | { | + | myInput update |
- | | + | |
- | myObjectExample : myArrayOfObjects.aString | + | |
} | } | ||
</ | </ | ||
- | |||
- | ===== Типы данных ===== | ||
- | |||
- | * Number / Numbers (dw:: | ||
- | * String / Strings (dw:: | ||
- | * Boolean / Boolean (dw::Core Type) | ||
- | * Array / Arrays (dw:: | ||
- | * Object / Object (dw::Core Type) или {} | ||
< | < | ||
%dw 2.0 | %dw 2.0 | ||
- | + | output | |
- | output json | + | |
--- | --- | ||
- | typeOf({}) | + | payload map ((item) -> |
+ | item.ServiceDetails update | ||
+ | case Designation at .Designation if (Designation == " | ||
+ | }) | ||
</ | </ | ||
Строка 1574: | Строка 1291: | ||
* https:// | * https:// | ||
+ | * https:// | ||
+ | * https:// | ||
+ | * https:// |