Различия

Показаны различия между двумя версиями страницы.

Ссылка на это сравнение

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
develop:mule:dataweave [2024/02/14 02:35] mirocowdevelop:mule:dataweave [2024/03/06 22:19] (текущий) – [Ссылки] mirocow
Строка 1: Строка 1:
-{{tag>language languages datawave mule}}+{{tag>language languages datawiave mule}}
  
-====== DataWeave ======+===== DataWeave =====
  
 <code dw> <code dw>
Строка 18: Строка 18:
 </code> </code>
  
-===== mapObject =====+<note tip>IDE https://dataweave.mulesoft.com/learn/playground</note> 
 +===== Oprators =====
  
-Функция  mapObject используется для преобразования данных, содержащихся в объектеЭто делается путем перебора каждой пары ключ/значение в объекте и применения преобразования к каждому ключу и значениюОн принимает объект и лямбду, которая принимает 3 параметразначениеключ и индекси возвращает новый объектНаконецвся функция возвращает объект.+  * 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 selectorfor examplein a case that uses the expression payload.root.a.@ to return the attributes and values of the input payload <root> <a attr1="foo" attr2="bar" /></root> within the array of objects { "attr1": "foo""attr2": "bar" }                                                                                                                                                                                                                                              
 +==== Condition ====
  
 <code> <code>
Строка 26: Строка 34:
 output application/json output application/json
 --- ---
-{"a":"b","c":"d"} mapObject (value,key,index) -> { (index) : { (value):key} }+{ 
 +    "result": if (vars.myVar == null) "myVar is nullelse "myVar has a value set" 
 +}
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output json+var myVar = { country : "India"
 +output application/json
 --- ---
-payload mapObject (value, key, index-> { +if (myVar.country == "UAE"
-  (upper(key))value +  { currency"EUR" } 
-}+else { currency: "RUPEES" }
 </code> </code>
  
Строка 41: Строка 52:
 %dw 2.0 %dw 2.0
 output application/json output application/json
-var user = {"firstName": "Manik", "lastName": "Magar", "addressLine1""Address line 1"} +var user = {"firstName": "Manik", "lastName": "Magar", "Address Line1" : "Address line 1"}
-var userList = [{"firstName": "Manik", "lastName": "Magar", "addressLine1" : "Address line 1"}+
- {"firstName": "Om", "lastName": "Magar", "addressLine1" : "Address line 2"} +
-]+
 --- ---
-+name : user mapObject { 
- mapObject: user mapObject (value:String, key:Key, index:Number) -> {  + ('$$' : '$'when ($ contains 'Ma')
- '$key-$index': value +
- }, +
- +
- pluck: user pluck (value, key, index) -> (key ++ '-++ index ++ '-' ++ value),     +
- +
- filter: user filterObject ((value, key, index) -> (index < 1)),  +
- filter2: userList filter ((value, index) -> (index < 1)),  +
- +
- groupBy1 : user groupBy (value, key) -> key endsWith 'Name',     +
- groupBy2 : userList groupBy ((value, index-> value.lastName)    +
 } }
 </code> </code>
- 
- 
-===== Working with Objects / dw::core::Objects ===== 
- 
-  * **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::core::Arrays ===== 
- 
-  * **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 ===== 
- 
-Функция уменьшения используется для выполнения любых вычислений во время итерации массива, поэтому результат вычислений не теряется во время итерации. Для каждого элемента входного массива по порядку сокращение применяет лямбда-выражение (функцию) сокращения, а затем заменяет аккумулятор новым результатом. Лямбда-выражение может использовать как текущий элемент входного массива, так и текущее значение аккумулятора. 
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output json+var aRecord = 
 + [ 
 +    "bookId":"101", 
 +    "title":"world history", 
 +    "price":"19.99" 
 + ] 
 +output application/xml
 --- ---
-payload reduce (ntotal) -> total + n+{ examples: 
 +    { 
 +       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) -&gt; 
 +         if (idValue as Number == 101) idValue as Number 
 +         else "not 101" 
 +    } 
 +}
 </code> </code>
  
Строка 113: Строка 87:
 %dw 2.0 %dw 2.0
 output application/json output application/json
 +var user = {"firstName": "Manik", "lastName": "Magar", "Address Line1" : "Address line 1"}
 --- ---
-[2, 3] reduce ($ + $$)+name : user filter ($ contains "Ma") 
 +</code>
  
-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 
-</code> 
  
-<code> 
-%dw 2.0 
-output application/json 
---- 
-[2,3] reduce ((item, acc = 4) -> acc + item) 
  
-Here 
  
-    [2,3] – is the input array 
-    acc will take the initialized value = 4 
-    item will take 1st item value = 2 (as acc is initialized) 
-    Loop count = no of item in array (as acc is initialized) = 2 
-        Acc = acc + item -> 4 + 2 -> 6 
-        Acc = acc + item -> 6 + 3 -> 9 
  
-So result will be 9 +==== Functions ====
-</code>+
  
-===== groupBy =====+  * Named functions 
 +  * Lambdas 
 +  * Passing functions to other functions 
 +  * Calling 2-arity functions with infix notation 
 +  * $, $$, $$$ syntax
  
-Функция groupBy принимает список объектов [x1,…,xn] и некоторую функцию f. Затем она отображает f в списке, давая список объектов [f(x1),…,f(xn)], и использует эти значения для выполнения операции groupBy. Эта функция полезна для группировки элементов массива на основе некоторого значения, которое генерируется из каждого элемента массива.+=== Лямда функции / Functions as Values ===
  
-<code> +Полезность лямбд становится очевиднойкогда мы объединяем две идеи:
-%dw 2.0 +
-output json +
---- +
-payload groupBy (nidx) -> isEven(n) +
-</code>+
  
-<code> +  * Лямбды — это значения, такие же, как строки, объекты и логические значения
-%dw 2.0 +  * Значения могут передаваться функциям в качестве аргументова также возвращаться из функций.
-output json +
---- +
-payload groupBy (nidx) -> n.dayOfWeek +
-</code>+
  
-<code> +В DataWeave функции и лямбды (анонимные функциимогут передаваться как значения или присваиваться переменным. 
-%dw 2.0 +
-output application/json +
-var user = {"firstName": "Manik", "lastName": "Magar", "Address Line1" : "Address line 1"} +
---- +
-user groupBy ((value, key-> if (key contains 'Name') "Names" else "Address"+
-</code> +
-===== distinctBy =====+
  
-Выполняет итерацию по массиву и возвращает уникальные элементы в нем. DataWeave использует результат применения предоставленной лямбды в качестве критерия уникальности. Эта версия DifferentBy находит уникальные значения в массиве. Другие версии действуют на объект и обрабатывают нулевое значение.+DataWeave предоставляет несколько способов создания функций. Точно так же, как у нас есть именованные функции, у нас есть функции без именназываемые лямбда-выражениями. Лямбда — это значение в DataWeave, такое же, как строкаобъект и логическое значение. При использовании лямбда-выражений в теле файла DataWeave в сочетании с такой функцией, как карта, его атрибутам можно либо дать явное имя, либо оставить анонимным, и в этом случае на них можно ссылаться как $, $$ и т. д.
  
-Эта функция полезна, когда вам нужно удалить повторяющиеся элементы из массива+<note tip>Другими словами, лямбды становятся полезными, когда вы хотите передать функции в качестве аргументов другим функциям или вернуть функцию из функции.</note>
  
 <code> <code>
 %dw 2.0 %dw 2.0
 output json output json
---- 
-payload distinctBy $.id 
-</code> 
  
-===== map =====+fun isOddNum(n) = 
 +  (n mod 2) == 1
  
-Функция карты используется для преобразования данныхсодержащихся в массивеЭто делается путем перебора элементов массива и применения преобразования к каждому элементуРезультат преобразования собирается вместе и выводится в виде массива преобразованных элементов+// Generate [1, 2, ..., 5] 
- +var numbers = (1 to 5)
-Перебирает элементы массива и выводит результаты в новый массив. +
- +
-<code> +
-%dw 2.0 +
-output application/json+
 --- ---
-+filter(numbers, (nidx) -> isOddNum(n))
-    "candidatedetails": payload.employee map((item,index) -> +
-        "fname":item.FirstName ++ " " ++ item.LastName +
-    }) +
-}+
 </code> </code>
  
Строка 203: Строка 136:
 %dw 2.0 %dw 2.0
 output json output json
---- 
-payload map (n, idx) -> n + 1 
-</code> 
  
-<code> +var numbers = (1 to 5)
-%dw 2.0 +
-output json+
 --- ---
-payload.items.*name map ( +filter(numbers, (nidx) -> (n mod 2) == 1)
-    (itemindex) -> {name: item} +
-)+
 </code> </code>
- 
-===== pluck ===== 
- 
-это функция, используемая для преобразования свойств и значений этих свойств объекта в массив свойств, массив значений и массив индексов этих свойств. Эту функцию можно использовать, если вам нужно преобразовать объект в массив. 
  
 <code> <code>
Строка 224: Строка 146:
 output json output json
 --- ---
-payload pluck (v,k,idx) -> {(k): v}+(() -> 2 + 3)()
 </code> </code>
  
Строка 230: Строка 152:
 %dw 2.0 %dw 2.0
 output application/json output application/json
-var requestBody +var toUser (user) -> 
-+  firstNameuser.field1
-    "name":"Jack", +  lastNameuser.field2
-    "name":"James"+
-    "name":"Joseph"+
 } }
 --- ---
 { {
-valuerequestBody pluck $, +  "user" toUser(payload)
-keys: requestBody pluck $$, +
-indexes: requestBody pluck $$$+
 } }
 </code> </code>
  
-<code> +=== Логические операторы Logical Operators ===
-%dw 2.0 +
-output application/json +
-var requestBody +
-+
-"car" :  +
-+
-"Make&Model": "Maruti Suzuki Swift", +
-"MakeYear": 2017, +
-"Color": "Red", +
-"Type": "Hatchback", +
-}, +
-"car" :  +
-+
-"Make&Model": "Maruti WagonR", +
-"MakeYear": 2018, +
-"Color": "Brown", +
-"Type": "Hatchback", +
-}, +
-"car" :  +
-+
-"Make&Model": "Honda City", +
-"MakeYear": 2017, +
-"Color": "Red", +
-"Type": "Sedan", +
-}, +
-"car" :  +
-+
-"Make&Model": "Ford Figo", +
-"MakeYear": 2017, +
-"Color": "Black", +
-"Type": "Hatchback", +
-+
-+
---- +
-car:requestBody pluck $ filter $.Color == "Red" +
-</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.
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var myInput +output json 
-    "name": "Ken", +var age 2
-    "lastName":"Shokida", +
-    "age": 30, +
-    "address":+
-        "street": "Amenabar", +
-        "zipCode": "AB1234" +
-    } +
-+
-output application/json+
 --- ---
-myInput update { +age < 10
-    case age at .age -> age + 1 +
-    case s at .address.street -> "First Street" +
-}+
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
 +var myArray = [1,2,3,4,5]
 +var myMap = myArray map not (($ mod 2) == 0)
 output application/json output application/json
 --- ---
-payload update +
-    case s at .addresses[0-> { +  "not"[ 
-        "street": "Second Street", +    "notTrue" : not true, 
-        "zipCode": "ZZ123+    "notFalse" : not false, 
-    }+    "myMapWithNot" : myMap 
 +  ], 
 +  "and" : 
 +    "andTrueFalse: true and false
 +    "andIsTrue" : (1 + 1 == 2) and (2 + 2 == 4), 
 +    "andIsFalse: (1 + 1 == 2) and (2 + 2 == 2) 
 +  ], 
 +  "or" : [ 
 +    "orTrueFalse" : true or false, 
 +    "orIsTrue" : (1 + 1 == 2) or (2 + 2 == 2), 
 +    "orIsFalse" : (1 + 1 == 1) or (2 + 2 == 2) 
 +  ], 
 +  "!-vs-not" : [ 
 +      "example-!" : (! true or true), 
 +      "example-not" : (not true or true) 
 +  ]
 } }
 </code> </code>
Строка 320: Строка 219:
 <code> <code>
 %dw 2.0 %dw 2.0
 +var orNot = if (1 + 1 == 4 or not 1 == 2) {"answer": "orNot - Condition met"}
 +             else {"answer": "nope"}
 +var andNot = if (1 + 1 == 2 and not 1 == 2) {"answer": "andNot - Condition met"}
 +             else {"answer": "nope"}
 +var notWithAndNot = if (not (1 + 1 == 2 and not 1 == 1)) {"answer": "notWithAndNot - Condition met"}
 +              else {"answer": "nope"}
 output application/json output application/json
 --- ---
-payload update +"answers"
-    case name at .user.@name -> upper(name)+  [ 
 +    orNot, 
 +    andNot, 
 +    notWithAndNot 
 +  ]
 } }
 </code> </code>
 +
 +=== Types ===
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var theFieldName = "name" 
 output application/json output application/json
 --- ---
-payload update +
-    case s at ."$(theFieldName)" -"Shoki"+  /* 
 +   * A multi-line 
 +   * comment here. 
 +   */ 
 +  myString: "hello world"
 +  myNumber: 123, 
 +  myFloatingPointNumber: 123.456, 
 +  myVeryBigNumber: 12341234134123412341234123, 
 +  myDate: |2018-12-07|, 
 +  myTime: |11:55:56|, 
 +  myDateTime: |2018-10-01T23:57:59-03:00|, 
 +  myBoolean: true, 
 +  myArray: [ 1, 2, 3, 5, 8], 
 +  myMixedArray: [ 1, 2, "blah", { hello: "there" } ], 
 +  myObjectKeyValuePair: { innerKey: "innerValue" }, 
 +  myObjectWithConditionalField: { a : { b : 1, ( c : 2 ) if true, (d : 4) if false } }, 
 +  myNull: null, 
 +  myBinary: "abcd1234123" as Binary 
 +  //A one-line comment here.
 } }
 </code> </code>
 +===== dw::* =====
 +
 +==== dw::core::Arrays / Working with Array ====
 +
 +  * **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 ===
  
 <code> <code>
 %dw 2.0 %dw 2.0
 +import divideBy from dw::core::Objects
 output application/json output application/json
 --- ---
-payload map ((user) -> +{ "a": 1, "b": true, "a": 2, "b": false, "c":divideBy 2 
-    user update { +
-        case name at .name if(name == "Ken") -> name ++ (Leandro)" +
-        case name at .name if(name == "Tomo") -> name ++ (Christian)" +
-    } +
-)+
 </code> </code>
 +=== drop ===
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var myInput = [{"lastName""Doe"}{"lastName": "Parker", "name": "Peter}]+import * from dw::core::Arrays 
 +var samplearray = ["124""35454", "Sachin","Amit"]
 output application/json output application/json
 --- ---
-myInput  map ((value) -> +  
-    value update { +drop(samplearray, 2)
-        case name at .name! -> if(name == null) "JOHN" else upper(name) +
-    } +
-)+
 </code> </code>
 +
 +=== indexOf ===
  
 <code> <code>
 %dw 2.0 %dw 2.0
 +import * from dw::core::Arrays
 +var samplearray = ["124", "35454", "Sachin","Amit"]
 output application/json output application/json
 --- ---
-payload update { +  
-    //equivalent expression: +indexOf(samplearray, "Sachin")
-    //case age at .age -> age + 1 +
-    case .age -> $ + 1 +
-    case .address.street -> "First Street" +
-}+
 </code> </code>
 +
 +=== join ===
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var myInput = { +import * from dw::core::Arrays 
-    "name": "Ken", +  
-    "lastName":"Shokida", +var items [{id: "12", name:"Tea"},{id: "22", name:"Salt"},{id: "3", name:"Soap"},{id"5", name:"Butter"}] 
-    "age": 30 +  
-}+var Prices = [{Id: "12", price:123},{Id: "3", price:24}, {Id: "22", price:20}, {Id: "4", price:456}] 
 + 
 output application/json output application/json
 --- ---
-myInput mapObject ((value,key) -> +join(items, Prices, (item) -> item.id, (price-> price.Id
-    if(key as String == "age") +
-       {(key): value as Number + 1} +
-    else +
-       {(key): value} )+
 </code> </code>
 +=== takeWhile ===
 +
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var myInput = { +import * from dw::core::Arrays
-    "name""Ken", +
-    "lastName":"Shokida", +
-    "age"30 +
-}+
 output application/json output application/json
 +var arr = [1,2,3,4,1,2]
 --- ---
-myInput update { +  
-    case age at .age -> age + 1 +arr takeWhile $ &lt;= 2 
-}+
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
 +import * from dw::core::Objects
 output application/json output application/json
 +var obj = {
 +  "a": 1,
 +  "b": 2,
 +  "c": 5,
 +  "d": 1
 +}
 --- ---
-payload map ((item) -> +obj takeWhile ((value, key) ->  value < 3)
-    item.ServiceDetails update { +
-        case Designation at .Designation if (Designation == "Clerk") ->  "Assistant Manager" +
-})+
 </code> </code>
 +==== dw::Core ====
  
-===== flatten =====+=== distinctBy ===
  
-Для перемещения элементов из подмассивов в родительский массив, удаления подмассивов и преобразования всех пар ключ-значение в список объектов в родительском массиве. С помощью функции Flatten несколько массивов объединяются в один массив.+Выполняет итерацию по массиву и возвращает уникальные элементы в нем. DataWeave использует результат применения предоставленной лямбды в качестве критерия уникальности. Эта версия DifferentBy находит уникальные значения в массиве. Другие версии действуют на объект и обрабатывают нулевое значение.
  
-  * **items** The input array of arrays made up of any supported types.+Эта функция полезна, когда вам нужно удалить повторяющиеся элементы из массива
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/json+output json
 --- ---
-flatten(payload)+payload distinctBy $.id
 </code> </code>
  
Строка 429: Строка 381:
 %dw 2.0 %dw 2.0
 output application/json output application/json
-var array1 = [1,2,3+var str = [1,2,3,4,5,6,7
-var array2 = [4,5,6] +var str1= [4,5,6,7,1]
-var array3 = [7,8,9] +
-var arrayOfArrays = [array1array2array3]+
 --- ---
-flatten(arrayOfArrays)+(str ++ str1) distinctBy ((item, index) ->item )
 </code> </code>
  
-===== splitBy ===== +=== Filter Arrays ===
- +
-Разбивает строку на массив строк на основе входного значения или соответствует части этой входной строки. Он отфильтровывает соответствующую часть из возвращаемого массива. Строка или регулярное выражение Java, используемое для разделения строки. Если какая-то часть строки не соответствует, функция вернет исходную неразбитую строку в массиве. +
- +
-Эта версия splitBy принимает регулярное выражение Java (регулярное выражение), соответствующее входной строке. Регулярное выражение может соответствовать любому символу во входной строке. Обратите внимание, что splitBy выполняет противоположную операцию joinBy. +
- +
-  * **text** The input string to split. +
-  * **regex** A Java regular expression used to split the string. If it does not match some part of the string, the function will return the original, unsplit string in the array.+
  
 <code> <code>
Строка 450: Строка 393:
 output application/json output application/json
 --- ---
-"splitters" { +{ 
-   "split1" "a-b-c" splitBy(/^*.b./)+    idpayload.Id, 
-   "split2" "hello world" splitBy(/\s/)+    markCodepayload.marketCode
-   "split3" "no match" splitBy(/^s/)+    languageCodepayload.languageCode
-   "split4" "no match" splitBy(/^n../), +    usernamepayload.profile.base.username
-   "split5"a1b2c3d4A1B2C3DsplitBy(/^*[0-9A-Z]/) +    phoneNumber: (payload.profile.base.phone filter ($.activeInd == "Yand $.primaryInd== "Y")).number default []
-  }+
 } }
 </code> </code>
  
 +Infix Notation: Long-Hand
 <code> <code>
-%dw 2.0 +[ ] filter (valueindex-> (condition 
-output application/json +
---- +
-{ "splitters" : { +
-    "split1" : "a-b-c" splitBy("-"), +
-    "split2" : "hello world" splitBy("")+
-    "split3" : "first,middle,last" splitBy(","), +
-    "split4" : "no split" splitBy("NO") +
-   } +
-}+
 </code> </code>
  
 +Infix Notation: $ syntax 
 <code> <code>
-%dw 2.0 +[ ] filter (<condition using $, $$>
-output application/java +
---- +
-payload splitBy(" ")+
 </code> </code>
  
 +Prefix Notation
 <code> <code>
-%dw 2.0 +filter([ ], (value, index) -(condition))
-output application/java +
---- +
-payload splitBy(/s/)+
 </code> </code>
  
 +Filter Expression
 <code> <code>
-%dw 2.0 +[ ]  [? (<boolean_expression>]
-output application/json +
---- +
-"192.88.99.0/24" splitBy(/[.\/]/)+
 </code> </code>
  
Строка 498: Строка 426:
 output application/json output application/json
 --- ---
-"192.88.99.0splitBy(".")+["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL"
 +filter  
 +(value) -> (value contains "GO")
 </code> </code>
- 
-===== read ===== 
- 
-  * **stringToParse** The string or binary to read. 
-  * **contentType** A supported format (or content type). Default: application/dw. 
-  * **readerProperties** Optional: Sets reader configuration properties. For other formats and reader configuration properties, see Supported Data Formats. 
  
 <code> <code>
 %dw 2.0 %dw 2.0
 output application/json output application/json
-var inputData= 
-"name,age,salary 
-Joseph,34,3000 
-James,32,5000" 
 --- ---
-read(inputData,"application/csv")+["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL"
 +filter 
 +(value, index) -> ((index mod 2) == 0)
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var myVar = "Some, Body" 
 output application/json output application/json
 --- ---
-read(myVar,"application/csv",{header:false})[0]+["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL", "V", "COST"filter ($endsWith("A"))
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/xml+output application/json
 --- ---
-read('"hello: "world" }','application/json')+payload 
 +filter 
 +(value, index) -> ((value.cik_str mod 2) == 1) and 
 +(index > 5) and 
 +(value.ticker startsWith  ("T"))
 </code> </code>
- 
-===== readUrl ===== 
- 
-  * **url** The URL string to read. It also accepts a classpath-based URL. for example: classpath:\/\/myfolder/myFile.txt where myFolder is located under src/main/resources in a Mule project. Other than the URL, readURL accepts the same arguments as read. 
-  * **contentType** A supported format (or MIME type). Default: application/dw. 
-  * **readerProperties** Optional: Sets reader configuration properties. For other formats and reader configuration properties, see Supported Data Formats. 
  
 <code> <code>
Строка 543: Строка 462:
 output application/json output application/json
 --- ---
-readUrl("classpath://employee.json","application/json")+["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL", "V", "COST"] [?( $ contains "GO" )]
 </code> </code>
  
-<code> 
-%dw 2.0 
-var myJsonSnippet = readUrl("classpath://myJsonSnippet.json", "application/json") 
-output application/csv 
---- 
-(myJsonSnippet.results map(item) -> item.profile) 
-</code> 
  
-<code> +== Инфиксная запись Infix Notation ==
-%dw 2.0 +
-output application/json +
---- +
-readUrl("https://jsonplaceholder.typicode.com/users/5","application/json"+
-</code>+
  
-<code> +Когда вы пишете арифметическое выражениетакое как B * C, форма выражения предоставляет вам информацию, позволяющую правильно его интерпретироватьВ этом случае мы знаемчто переменная B умножается на переменную C, поскольку между ними в выражении появляется оператор умножения *Этот тип записи называется инфиксным , поскольку оператор находится между двумя операндаминад которыми он работает.
-%dw 2.0 +
-output application/json +
-var inputData=readUrl("https://jsonplaceholder.typicode.com/users/5","application/json"+
---- +
-+
-    name: inputData.name, +
-    username: inputData.username, +
-    email: inputData.email +
-+
-</code>+
  
-===== Condition =====+До сих пор мы вызывали фильтр, используя префиксную запись. При использовании префиксной записи имя функции помещается перед аргументами. Если функция принимает два аргумента, как это делает фильтр, DataWeave позволяет вызывать ее с инфиксной записью. 
 + 
 +<note tip>Обратите внимание на дополнительные круглые скобки вокруг первой лямбды. Круглые скобки вокруг лямбда-выражений помогают DataWeave определить, где начинается и заканчивается лямбда-выражение.</note>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/json+output json 
 + 
 +var numbers = (1 to 5)
 --- ---
-+numbers filter ((n, idx) -> (n mod 2) == 1)
-    "result": if (vars.myVar == null"myVar is null" else "myVar has a value set" +
-}+
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var myVar = { country : "India"+output json
-output application/json +
---- +
-if (myVar.country == "UAE"+
-  { currency: "EUR"+
-else { currency: "RUPEES"+
-</code>+
  
-<code> +var numbers (to 5)
-%dw 2.0 +
-output application/json +
-var user {"firstName": "Manik", "lastName": "Magar", "Address Line1" : "Address line 1"}+
 --- ---
-name : user mapObject { +numbers 
- ('$$' : '$'when ($ contains 'Ma'+  filter ((n, idx-> (n mod 2) == 1
-}+  filter ((n, idx) -> (n > 3))
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var aRecord = +output json
- [ +
-    "bookId":"101", +
-    "title":"world history", +
-    "price":"19.99" +
- ] +
-output application/xml+
 --- ---
-{ examples: +[ ] filter (valueindex) -(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) -&gt; +
-         if (idValue as Number == 101idValue as Number +
-         else "not 101" +
-    } +
-}+
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/json +output json
-var user = {"firstName": "Manik", "lastName": "Magar", "Address Line1" : "Address line 1"}+
 --- ---
-name : user filter ($ contains "Ma")+[ ] filter (<condition using $, $$>
 </code> </code>
  
-===== Filters ===== +== Prefix Notation  ==
- +
-==== filter ====+
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/json+output json
 --- ---
-+filter([ ](valueindex) -> (condition))
-    id: payload.Id, +
-    markCode: payload.marketCode, +
-    languageCode: payload.languageCode, +
-    username: payload.profile.base.username, +
-    phoneNumber: (payload.profile.base.phone filter ($.activeInd == "Y" and $.primaryInd== "Y")).number default [] +
-}+
 </code> </code>
- +=== filterObject ===
-==== filterObject ====+
  
 Оператор  filterObject перебирает список пар ключ-значение в объекте и применяет выражение, которое возвращает только соответствующие объекты, отфильтровывая остальные из выходных данных. Выражение должно возвращать значение  true или  false. Если выражение возвращает  true ключ, значение или индекс объекта, объект фиксируется в выходных данных. Если он возвращает  false какой-либо из них, объект отфильтровывается из вывода. Если совпадений нет, выходной массив будет пустым. Оператор  filterObject перебирает список пар ключ-значение в объекте и применяет выражение, которое возвращает только соответствующие объекты, отфильтровывая остальные из выходных данных. Выражение должно возвращать значение  true или  false. Если выражение возвращает  true ключ, значение или индекс объекта, объект фиксируется в выходных данных. Если он возвращает  false какой-либо из них, объект отфильтровывается из вывода. Если совпадений нет, выходной массив будет пустым.
Строка 672: Строка 534:
 Prefix Notation  Prefix Notation 
 <code> <code>
-filterOject({ }, (value, index) -> (condition))+filterObject({ }, (value, index) -> (condition))
 </code> </code>
  
Строка 754: Строка 616:
 --- ---
 payload payload
-filterO +filterObject
-bject+
 $ is Array $ is Array
 </code> </code>
Строка 789: Строка 650:
 --- ---
 payload [?( $.ticker contains "GO" )] payload [?( $.ticker contains "GO" )]
-</code> 
- 
-==== Filter Arrays ==== 
- 
-Infix Notation: Long-Hand 
-<code> 
-[ ] filter (value, index) -> (condition)   
-</code> 
- 
-Infix Notation: $ syntax  
-<code> 
-[ ] filter (<condition using $, $$> 
-</code> 
- 
-Prefix Notation 
-<code> 
-filter([ ], (value, index) -> (condition)) 
-</code> 
- 
-Filter Expression 
-<code> 
-[ ]  [? (<boolean_expression>) ] 
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/json+output application/json  
 --- ---
-["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL"+payload filterObject ((value, key) ->  
-filter  +    (key as String != "first name")  
-(value) -> (value contains "GO")+    and (key as String != "last name"
 +)
 </code> </code>
 +=== flatten ===
  
-<code> +Для перемещения элементов из подмассивов в родительский массивудаления подмассивов и преобразования всех пар ключ-значение в список объектов в родительском массиве. С помощью функции Flatten несколько массивов объединяются в один массив.
-%dw 2.0 +
-output application/json +
---- +
-["AAPL""MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL"+
-filter +
-(value, index) -> ((index mod 2) == 0) +
-</code>+
  
-<code> +  * **items** The input array of arrays made up of any supported types.
-%dw 2.+
-output application/json +
---- +
-["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL", "V", "COST"] filter ($endsWith("A")) +
-</code>+
  
 <code> <code>
Строка 842: Строка 671:
 output application/json output application/json
 --- ---
-payload +flatten(payload)
-filter +
-(value, index) -> ((value.cik_str mod 2) == 1) and +
-(index > 5) and +
-(value.ticker startsWith  ("T"))+
 </code> </code>
  
Строка 852: Строка 677:
 %dw 2.0 %dw 2.0
 output application/json output application/json
 +var array1 = [1,2,3]
 +var array2 = [4,5,6]
 +var array3 = [7,8,9]
 +var arrayOfArrays = [array1, array2, array3]
 --- ---
-["AAPL", "MSFT", "NVDA", "TSLA", "CRM", "GOOG", "GOOGL", "V", "COST"] [?$ contains "GO" )]+flatten(arrayOfArrays)
 </code> </code>
-===== Functions =====+=== groupBy ===
  
-  * Named functions +Функция groupBy принимает список объектов [x1,…,xn] и некоторую функцию f. Затем она отображает f в спискедавая список объектов [f(x1),…,f(xn)], и использует эти значения для выполнения операции groupBy. Эта функция полезна для группировки элементов массива на основе некоторого значения, которое генерируется из каждого элемента массива.
-  * Lambdas +
-  * Passing functions to other functions +
-  * Calling 2-arity functions with infix notation +
-  * $, $$, $$$ syntax +
- +
-==== Инфиксная запись / Infix Notation ==== +
- +
-Когда вы пишете арифметическое выражение, такое как B * C, форма выражения предоставляет вам информацию, позволяющую правильно его интерпретировать. В этом случае мы знаем, что переменная B умножается на переменную C, поскольку между ними в выражении появляется оператор умножения *. Этот тип записи называется инфиксным , поскольку оператор находится между двумя операндами, над которыми он работает+
- +
-До сих пор мы вызывали фильтр, используя префиксную запись. При использовании префиксной записи имя функции помещается перед аргументами. Если функция принимает два аргумента, как это делает фильтр, DataWeave позволяет вызывать ее с инфиксной записью. +
- +
-<note tip>Обратите внимание на дополнительные круглые скобки вокруг первой лямбды. Круглые скобки вокруг лямбда-выражений помогают DataWeave определить, где начинается и заканчивается лямбда-выражение.</note>+
  
 <code> <code>
 %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 (n, idx) -> isEven(n)
 </code> </code>
  
Строка 883: Строка 698:
 %dw 2.0 %dw 2.0
 output json output json
- 
-var numbers = (1 to 5) 
 --- ---
-numbers +payload groupBy (n, idx) -> n.dayOfWeek
-  filter ((n, idx) -> (mod 2) == 1) +
-  filter ((n, idx) -> (n > 3))+
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output json+output application/json 
 +var user = {"firstName": "Manik", "lastName": "Magar", "Address Line1" : "Address line 1"}
 --- ---
-[ ] filter (value, index) -> (condition)+user groupBy ((value, key) -> if (key contains 'Name') "Names" else "Address")
 </code> </code>
  
-<code> +=== map ===
-%dw 2.0 +
-output json +
---- +
-[ ] filter (<condition using $, $$>)  +
-</code>+
  
-==== Prefix Notation  ====+Функция карты используется для преобразования данных, содержащихся в массиве. Это делается путем перебора элементов массива и применения преобразования к каждому элементу. Результат преобразования собирается вместе и выводится в виде массива преобразованных элементов. 
 + 
 +Перебирает элементы массива и выводит результаты в новый массив.
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output json+output application/json
 --- ---
-filter([ ], (value, index) -> (condition))+
 +    "candidatedetails": payload.employee map((item,index) -> 
 +        "fname":item.FirstName ++ " " ++ item.LastName 
 +    }) 
 +}
 </code> </code>
- 
-==== Лямда функции / Functions as Values ==== 
- 
-Полезность лямбд становится очевидной, когда мы объединяем две идеи: 
- 
-  * Лямбды — это значения, такие же, как строки, объекты и логические значения. 
-  * Значения могут передаваться функциям в качестве аргументов, а также возвращаться из функций. 
- 
-В DataWeave функции и лямбды (анонимные функции) могут передаваться как значения или присваиваться переменным.  
- 
-DataWeave предоставляет несколько способов создания функций. Точно так же, как у нас есть именованные функции, у нас есть функции без имен, называемые лямбда-выражениями. Лямбда — это значение в DataWeave, такое же, как строка, объект и логическое значение. При использовании лямбда-выражений в теле файла DataWeave в сочетании с такой функцией, как карта, его атрибутам можно либо дать явное имя, либо оставить анонимным, и в этом случае на них можно ссылаться как $, $$ и т. д. 
- 
-<note tip>Другими словами, лямбды становятся полезными, когда вы хотите передать функции в качестве аргументов другим функциям или вернуть функцию из функции.</note> 
  
 <code> <code>
 %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, (n, idx) -> isOddNum(n))+payload map (n, idx) -> n + 1
 </code> </code>
  
Строка 943: Строка 737:
 %dw 2.0 %dw 2.0
 output json output json
- 
-var numbers = (1 to 5) 
 --- ---
-filter(numbers, (nidx) -> (n mod 2) == 1)+payload.items.*name map ( 
 +    (itemindex) -> {name: item} 
 +)
 </code> </code>
  
 <code> <code>
-%dw 2.0 
-output json 
---- 
-(() -> 2 + 3)() 
-</code> 
  
-<code> 
 %dw 2.0 %dw 2.0
 +var myVar = [
 +  { bookId: 101,
 +    title: "world history",
 +    price: "19.99"
 +  },
 +  {
 +    bookId: 202,
 +    title: 'the great outdoors',
 +    price: "15.99"
 +  }
 +]
 +var myVar2 = [
 +  {
 +    bookId: 101,
 +    author: "john doe"
 +  },
 +  {
 +    bookId: 202,
 +    author: "jane doe"
 +  }
 +]
 output application/json output application/json
-var toUser = (user) -> { 
-  firstName: user.field1, 
-  lastName: user.field2 
-} 
 --- ---
-+myVar map (item, index) -> using (id = item.bookId) 
-  "user" : toUser(payload)+ "id" : id, 
 + "topic" : item.title, 
 + "cost" : item.price as Number, 
 + (myVar2 filter ($.*bookId contains id) map (item) -> { 
 + author : item.author 
 + })
 } }
 </code> </code>
- 
-==== Именованные функции / Named Functions ==== 
- 
-Для создания функции в разделе объявлений скрипта, используется ключевое слово fun. Это связывает набор функций с именем.  
- 
-<note tip>Обратите внимание, что здесь нет ключевого слова return. Ключевое слово return не требуется, поскольку большая часть всего в DataWeave является выражением, а все выражения возвращают данные.</note> 
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output json +output application/java 
-  +fun process(obj: Object) = obj mapObject ((value, key) -> { 
-fun add(n, m) = +    (key): key match { 
-  n + m+        case "description" -> vars.descriptionValue 
 +        else -> value 
 +    } 
 +})
 --- ---
-add(1,2)+payload map ((itemindex) ->  
 +    process(item) 
 +)
 </code> </code>
 +=== mapObject ===
  
-<code> +Функция  mapObject используется для преобразования данныхсодержащихся в объекте. Это делается путем перебора каждой пары ключ/значение в объекте и применения преобразования к каждому ключу и значению. Он принимает объект и лямбдукоторая принимает 3 параметра: значениеключ и индекси возвращает новый объект. Наконец, вся функция возвращает объект.
-%dw 2.0 +
-output json +
-  +
-fun diff(n) = do { +
-  var start = n[0] +
-  var end = n[-1] +
-  --- +
-  end - start +
-+
-  +
---- +
-diff([19901995200220082021]) +
-</code>+
  
 <code> <code>
 %dw 2.0 %dw 2.0
 output application/json output application/json
-input payload application/json 
-var user = {"firstName": "Manik", "lastName" : "Magar"} 
-var foo = "bar" 
-fun getName(data) = (data.firstName ++ ' ' ++ data.lastName) 
-var toFullname = (data) -> (data.firstName ++ ' ' ++ data.lastName) 
 --- ---
-{ +{"a":"b","c":"d"} mapObject (value,key,index) -> { (index) (value):key} }
- "foo" : foo, +
- "getName" : getName(user), +
- "toFullname" : toFullname(user) +
-}+
 </code> </code>
- 
-==== $, $$, $$$ Syntax ==== 
- 
-HOF настолько распространены в библиотеке DataWeave, что существуют дополнительные синтаксические функции, которые упрощают их использование. Для функций, предоставляемых DataWeave, вы можете представить первый, второй и третий аргументы переданной лямбды как $, $$и $$$, соответственно. При этом вам не нужно указывать аргументы лямбды при передаче ее функции. 
- 
-  * **$**    Представляет текущее значение объекта. 
-  * **$$**    Представляет текущий ключ объекта. 
-  * **$$$**    Представляет текущий индекс объекта. 
  
 <code> <code>
 %dw 2.0 %dw 2.0
 output json output json
-  
-var numbers = (1 to 5) 
 --- ---
-numbers filter (($ mod 2== 1+payload mapObject (value, key, index) -> { 
-</code> +  (upper(key)): value 
- +}
-<code> +
-%dw 2.0 +
-output json +
---- +
-payload filter $.price &gt; 5+
 </code> </code>
  
Строка 1043: Строка 816:
 %dw 2.0 %dw 2.0
 output application/json output application/json
 +var user = {"firstName": "Manik", "lastName": "Magar", "addressLine1" : "Address line 1"}
 +var userList = [{"firstName": "Manik", "lastName": "Magar", "addressLine1" : "Address line 1"},
 + {"firstName": "Om", "lastName": "Magar", "addressLine1" : "Address line 2"}
 +]
 --- ---
 { {
- user: null filter ($.firstName == 'Manik'), + mapObject: user mapObject (value:Stringkey:Key, index:Number) -> {  
- + '$key-$index': value
- usernull mapObject +
- '$$': $+
  },  },
  
- users null map ((value, index) -> value.firstName) + pluckuser pluck (value, key, index) -> (key ++ '-' ++ index ++ '-' ++ value),    
-+
-</code>+
  
-===== 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 (valuekey) -> key endsWith 'Name'    
-Сопоставление с образцом — это еще один метод управления потоком, но он делает гораздо больше, чем выражение if/else, а синтаксис немного сложнее. Как и выражение if/elseсопоставление с образцом также возвращает одно значение+ groupBy2 : userList groupBy ((valueindex) -> value.lastName)   
  
-<code> 
-%dw 2.0 
-output json 
---- 
-payload.action match { 
-  case "buy"  -> “Buy at market price" 
-  case "sell" -> "Sell at market price" 
-  case "hold" -> “Hold asset" 
-  else   -> "Invalid input" 
 } }
 </code> </code>
  
-<code> +=== pluck ===
-%dw 1.0 +
-input payload application/json +
-output application/json +
-var data  "Hello I am from \"StackOverflow, Internet\"" +
---- +
-data scan /\w++, \w++|\w++/ reduce ($$ ++ $) +
-</code> +
-===== Управление потоком / Flow Control =====+
  
-  * do +это функция, используемая для преобразования свойств и значений этих свойств объекта в массив свойств, массив значений и массив индексов этих свойств. Эту функцию можно использовать, если вам нужно преобразовать объект в массив.
-  * if else +
-  * else if +
- +
- +
-==== do statement in flow ====+
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/json +output json
-fun myfun() = do { +
-    var name = "DataWeave" +
-    --- +
-    name +
-}+
 --- ---
-result: myfun() }+payload pluck (v,k,idx) -> {(k): v}
 </code> </code>
  
Строка 1104: Строка 851:
 %dw 2.0 %dw 2.0
 output application/json output application/json
-var myVar do +var requestBody 
-    var name "DataWeave+
-    --- +    "name":"Jack", 
-    name+    "name":"James", 
 +    "name":"Joseph"
 } }
 --- ---
-resultmyVar }+{ 
 +    valuerequestBody pluck $, 
 +    keys: requestBody pluck $$, 
 +    indexes: requestBody pluck $$$ 
 +}
 </code> </code>
  
Строка 1116: Строка 868:
 %dw 2.0 %dw 2.0
 output application/json output application/json
-fun test(p: String) do +var requestBody 
-    var a = "Foo++ p +
-    --- +    "car" 
-    a+    
 +        "Make&Model": "Maruti Suzuki Swift", 
 +        "MakeYear": 2017, 
 +        "Color": "Red", 
 +        "Type": "Hatchback", 
 +    }, 
 +    "car":  
 +    { 
 +        "Make&Model": "Maruti WagonR", 
 +        "MakeYear": 2018, 
 +        "Color": "Brown", 
 +        "Type": "Hatchback", 
 +    }, 
 +    "car":  
 +    { 
 +        "Make&Model": "Honda City", 
 +        "MakeYear": 2017, 
 +        "Color": "Red", 
 +        "Type": "Sedan", 
 +    }, 
 +    "car":  
 +    { 
 +        "Make&Model": "Ford Figo", 
 +        "MakeYear": 2017, 
 +        "Color": "Black", 
 +        "Type": "Hatchback", 
 +    }
 } }
 --- ---
-{ resulttest(Bar") }+car:requestBody pluck $ filter $.Color == "Red"
 </code> </code>
 +=== reduce ===
  
-==== Операторы условия / if else Condition in flow ====+Функция уменьшения используется для выполнения любых вычислений во время итерации массива, поэтому результат вычислений не теряется во время итерации. Для каждого элемента входного массива по порядку сокращение применяет лямбда-выражение (функцию) сокращения, а затем заменяет аккумулятор новым результатом. Лямбда-выражение может использовать как текущий элемент входного массива, так и текущее значение аккумулятора.
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var myVar = { country : "FRANCE"+output json
-output application/json+
 --- ---
-if (myVar.country == "USA") +payload reduce (n, total-> total + n
-  { currency: "USD"+
-else { currency: "EUR" }+
 </code> </code>
- 
-==== Операторы условия  / else if Condition in flow ==== 
  
 <code> <code>
Строка 1143: Строка 917:
 output application/json output application/json
 --- ---
-["Argentina""USA", "Brazil"map (country) -&gt; do { +[23reduce ($ + $$)
-  var hello = if(country == "Argentina") "Hola" +
-   else if(country == "USA") "Hello" +
-   else if(country == "Brazil") "Ola" +
-   else "Sorry! We don't know $(country)'s language." +
-   --- +
-   "$(helloDataWeave" +
-+
-</code>+
  
-<code> +Here
-%dw 2.0 +
-var myVar = { country : "India"+
-output application/json +
---- +
-if (myVar.country == "UAE"+
-  { currency: "EUR"+
-else { currency: "RUPEES"+
-</code>+
  
-<code> +    [2,3] – is the input array 
-%dw 2.0 +    acc -> $$ will take the 1st item value = 2 (as acc is not initialized) 
-var aRecord = +    $ 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 
-    "bookId":"101"+        Acc = ($=3 + $$=2= 5
-    "title":"world history", +
-    "price":"19.99" +
- ] +
-output application/xml +
---- +
-{ examples: +
-    +
-       ex1 : if (1 + 1 == 55true +
-             else false, +
-       ex2 : if ([1,2,3,4][1] == 1) 1 +
-             else "value of index is not 1", +
-       ex3 : if (isEmpty(aRecord.bookId)) "ID is empty" +
-         else "ID is not empty", +
-       ex4 : aRecord.bookId map (idValue-&gt; +
-         if (idValue as Number == 101idValue as Number +
-         else "not 101" +
-    } +
-+
-</code>+
  
-===== Логические операторы / Logical Operators ===== +So result will be 5
- +
-  * 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. +
- +
-<code> +
-%dw 2.0 +
-output json +
-var age = 2 +
---- +
-age < 10+
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var myArray = [1,2,3,4,5] 
-var myMap = myArray map not (($ mod 2) == 0) 
 output application/json output application/json
 --- ---
-+[2,3reduce ((itemacc 4-> acc item)
-  "not"[ +
-    "notTrue" : not true, +
-    "notFalse" : not false, +
-    "myMapWithNot" : myMap +
-  ], +
-  "and" : [ +
-    "andTrueFalse" : true and false, +
-    "andIsTrue" : (1 + 1 == 2) and (2 + 2 == 4), +
-    "andIsFalse" : (1 + 1 == 2) and (2 + 2 == 2) +
-  ]+
-  "or" : [ +
-    "orTrueFalse" : true or false, +
-    "orIsTrue"(1 + 1 == 2) or (2 + 2 == 2), +
-    "orIsFalse" : (1 + 1 == 1or (2 2 == 2) +
-  ], +
-  "!-vs-not" : [ +
-      "example-!" : (! true or true), +
-      "example-not" : (not true or true) +
-  ] +
-+
-</code>+
  
-<code> +Here
-%dw 2.0 +
-var orNot = if (1 + 1 == 4 or not 1 == 2) {"answer": "orNot - Condition met"+
-             else {"answer": "nope"+
-var andNot = if (1 + 1 == 2 and not 1 == 2) {"answer": "andNot - Condition met"+
-             else {"answer": "nope"+
-var notWithAndNot = if (not (1 + 1 == 2 and not 1 == 1)) {"answer": "notWithAndNot - Condition met"+
-              else {"answer": "nope"+
-output application/json +
---- +
-{ "answers"+
-  [ +
-    orNot, +
-    andNot, +
-    notWithAndNot +
-  ] +
-+
-</code>+
  
-===== Получение данных =====+    [2,3] – is the input array 
 +    acc will take the initialized value 
 +    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] +</code>
-  * 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) ====+
  
 <code> <code>
 %dw 2.0 %dw 2.0
-import * from dw::Crypto 
 output application/json output application/json
---- 
-{ “myRawData” : MD5(payload.^raw) } 
-</code> 
  
-<code> +var data = {"xyz": {"abc":["account":[{"value":"savings"}]]}}
-%dw 2.0 +
-output application/java+
 --- ---
-((payload.^raw as String) scan /encoding='([A-z0-9-]+)’/)[0][1]+data..value reduce $
 </code> </code>
  
-==== Raw Metadata Selector (.^customMetadataValue) ====+=== read ===
  
-<code> +  * **stringToParse** The string or binary to read. 
-%dw 2.+  * **contentType** A supported format (or content type)Default: application/dw. 
-output application/json +  * **readerProperties** OptionalSets reader configuration propertiesFor other formats and reader configuration propertiessee Supported Data Formats.
-var userName = “DataWeave” as String {myCustomMetadata: “customMetadataValue”} +
---- +
-{ +
-  “valueOfVariableMetaData”  userName.^myCustomMetadata, +
-  “valueOfVariable” :  userName, +
-+
-</code> +
- +
-==== Filter Selectors (myKey[?($ == “aValue”)]) ====+
  
 <code> <code>
 %dw 2.0 %dw 2.0
 output application/json output application/json
 +var inputData=
 +"name,age,salary
 +Joseph,34,3000
 +James,32,5000"
 --- ---
-{ users: payload.users.*name[?($ == “Mariano”)] }+read(inputData,"application/csv")
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
 +var myVar = "Some, Body"
 output application/json output application/json
 --- ---
-userspayload.users.*name[?( 1 == 1)] }+read(myVar,"application/csv",{header:false})[0]
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/json+output application/xml
 --- ---
-payload mapObject ($$) $[?($==”Mariano”)] }+read('"hello" "world" }','application/json')
 </code> </code>
  
-==== Selector Modifiers (!, ?) ====+=== readUrl ===
  
-  * ! оценивает выбор и завершается с ошибкой с сообщением об исключенииесли ключ отсутствует+  * **url** The URL string to read. It also accepts a classpath-based URL. for example: classpath:\/\/myfolder/myFile.txt where myFolder is located under src/main/resources in a Mule project. Other than the URLreadURL accepts the same arguments as read
-  * ? возвращает true, если выбранный ключ присутствует, и falseесли нет.+  * **contentType** A supported format (or MIME type). Default: application/dw. 
 +  * **readerProperties** Optional: Sets reader configuration properties. For other formats and reader configuration propertiessee Supported Data Formats.
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/xml+output application/json
 --- ---
-presentpayload.name?+readUrl("classpath://employee.json","application/json")
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/json+var myJsonSnippet = readUrl("classpath://myJsonSnippet.json", "application/json") 
 +output application/csv
 --- ---
-+(myJsonSnippet.results map(item) -> item.profile)
-  item: { +
-    typePresent : payload.product.@.”type”? +
-  } +
-}+
 </code> </code>
- 
-==== Namespace Selector (#) ==== 
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output text/plain+output application/json
 --- ---
-payload.order.#+readUrl("https://jsonplaceholder.typicode.com/users/5","application/json")
 </code> </code>
- 
-==== XML Attribute Selector (.@myKey) ==== 
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var myVar = read(‘<product id=”1″ type=”electronic”> 
-  <brand>SomeBrand</brand> 
-</product>’, ‘application/xml’) 
 output application/json output application/json
 +var inputData=readUrl("https://jsonplaceholder.typicode.com/users/5","application/json")
 --- ---
 { {
-  item+    nameinputData.name
-      { +    usernameinputData.username
-      “type” : myVar.product.@.”type”+    emailinputData.email
-      “name” myVar.product.brand+
-      “attributes”myVar.product.@ +
-    } +
-  ]+
 } }
 </code> </code>
 +=== splitBy ===
  
-==== Range selector (anIndex to anotherIndex) ====+Разбивает строку на массив строк на основе входного значения или соответствует части этой входной строки. Он отфильтровывает соответствующую часть из возвращаемого массива. Строка или регулярное выражение Java, используемое для разделения строки. Если какая-то часть строки не соответствует, функция вернет исходную неразбитую строку в массиве.
  
-Если вам нужно несколько последовательных значений из массива, DataWeave позволяет вам выбрать диапазон значений с помощью селектора диапазона (от [n до m]).+Эта версия splitBy принимает регулярное выражение Java (регулярное выражение), соответствующее входной строке. Регулярное выражение может соответствовать любому символу во входной строке. Обратите внимание, что splitBy выполняет противоположную операцию joinBy.
  
-<code> +  * **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 to 1] +
-</code>+
  
 <code> <code>
Строка 1395: Строка 1041:
 output application/json output application/json
 --- ---
-+{ "splitters"
-  slice[0,1,2][0 to 1]+   "split1" "a-b-c" splitBy(/^*.b./), 
-  last[0,1,2][-1 to 0]+   "split2" : "hello world" splitBy(/\s/), 
 +   "split3" : "no match" splitBy(/^s/)
 +   "split4" "no match" splitBy(/^n../), 
 +   "split5" : "a1b2c3d4A1B2C3D" splitBy(/^*[0-9A-Z]/) 
 +  }
 } }
 </code> </code>
Строка 1405: Строка 1055:
 output application/json output application/json
 --- ---
-+{ "splitters"
-  slice“DataWeave”[0 to 1]+    "split1" "a-b-c" splitBy("-")
-  middle “superfragilisticexpialadocious”[10 to 13]+    "split2" "hello world" splitBy("")
-  last: “DataWeave”[-1 to 0]+    "split3" : "first,middle,last" splitBy(","), 
 +    "split4" "no split" splitBy("NO"
 +   }
 } }
 </code> </code>
  
-==== Index Selector ([]) ====+=== valuesOf ===
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output json+output application/json
 --- ---
-payload[1]+valuesOf(payload.responses) filter ($.fieldname ~= "verifyemail")
 </code> </code>
- 
-==== Key-Value Pair Selector (.&myKey) ==== 
- 
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/xml+output application/java
 --- ---
-+payload splitBy(" ")
-  users: payload.users.&user +
-}+
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
- +output application/java
-var myData = { +
-  “people”:+
-    “person”:+
-      “name”: “Nial”, +
-      “address”:+
-        “street”:+
-          “name”: “Italia”, +
-          “number”: 2164 +
-        }, +
-        “area”: { +
-          “zone”: “San Isidro”, +
-          “name”: “Martinez” +
-        } +
-      } +
-    } +
-  } +
-+
-output application/xml+
 --- ---
-names: {(myData.people..&name)}+payload splitBy(/s/)
 </code> </code>
- 
-==== Descendants Selector (..) ==== 
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output json+output application/json
 --- ---
-payload..echo+"192.88.99.0/24" splitBy(/[.\/]/)
 </code> </code>
  
Строка 1470: Строка 1097:
 output application/json output application/json
 --- ---
-{ names: payload.people..name }+"192.88.99.0" splitBy(".")
 </code> </code>
  
-==== Multi-Value Selector (.*) ====+==== Working with Objects / dw::core::Objects ====
  
-<code> +  * **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. 
-</code>+  * **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 ===
  
 <code> <code>
 %dw 2.0 %dw 2.0
- +import everyEntry from dw::core::Objects
-var myArrayOfKeyValuePairs = [ “aString”“hello”, “aNum”2, “aString” “world” ] +
-var myArrayOfObjects = [ { “aString”“hello” }, { “aNum”: 2 }, { “aString” : “world” } ]+
 output application/json output application/json
 --- ---
 { {
-    myKeyValueExample myArrayOfKeyValuePairs.*aString+    a{} everyEntry (value, key) -> value is String
-    myObjectExample  myArrayOfObjects.*aString+    b{a: "", b: "123"} everyEntry (value, key) -> value is String, 
 +    c: {a: "", b: 123} everyEntry (value, key) -> value is String, 
 +    d: {a: "", b: 123} everyEntry (value, key) -> key as String == "a", 
 +    e: {a: ""} everyEntry (value, key) -> key as String == "a", 
 +    f: null everyEntry ((value, key) -> key as String == "a")
 } }
 </code> </code>
  
-==== Single-Value Selector ====+=== mergeWith ===
  
 <code> <code>
 %dw 2.0 %dw 2.0
- +import mergeWith from dw::core::Objects 
-output json+output application/json
 --- ---
-payload.age+{ "a" : true, "b" : 1} mergeWith { "a" : false, "c" : "Test"
 </code> </code>
 +
 +=== someEntry ===
  
 <code> <code>
 %dw 2.0 %dw 2.0
- +import someEntry from dw::core::Objects 
-output json+output application/json
 --- ---
 { {
-  fixedpayload.age+    a{} someEntry (value, key) -> value is String
-  dynamicpayload[payload.dynamicKey]+    b{a: "", b: "123"} someEntry (value, key) -> value is String, 
 +    c: {a: "", b: 123} someEntry (value, key) -> value is String, 
 +    d: {a: "", b: 123} someEntry (value, key) -> key as String == "a", 
 +    e: {a: ""} someEntry (value, key) -> key as String == "b", 
 +    f: null someEntry (value, key) -> key as String == "a"
 } }
 </code> </code>
 +==== dw::util::Values ====
  
-<code> +=== Selector Expressions (update Operator) ===
-%dw 2.0+
  
-var myObject = { user : “a” } +update оператор позволяет обновлять указанные поля структуры данных новыми значениями. 
-output application/json +Этот селектор соответствия может проверять совпадения с любым значением внутри объекта.
---- +
-{ myObjectExample : myObject.user } +
-</code>+
  
 <code> <code>
 %dw 2.0 %dw 2.0
- +var myInput = { 
-var myData = { +    "name""Ken", 
-  “people”{ +    "lastName":"Shokida"
-    “size” 1+    "age"30
-    “person”+    "address": { 
-      “name”: “Nial”+        "street""Amenabar"
-      “address: { +        "zipCode""AB1234"
-        street+
-          “name”: “Italia”, +
-          “number”: 2164 +
-        }, +
-        “area”+
-          “zone”: “San Isidro”, +
-          “name”: “Martinez” +
-        } +
-      }+
     }     }
-  } 
 } }
-output application/xml+output application/json
 --- ---
-myaddresses: myData.people.person.address }+myInput update { 
 +    case age at .age -> age + 1 
 +    case s at .address.street -> "First Street" 
 +}
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
- 
-var myArrayOfKeyValuePairs = [ “aString”: “hello”, “aNum”: 2, “aString” : “world” ] 
-var myArrayOfObjects = [ { “aString”: “hello” }, { “aNum”: 2 }, { “aString” : “world” } ] 
 output application/json output application/json
 --- ---
-+payload update 
-    myKeyValueExample : myArrayOfKeyValuePairs.aString+    case s at .addresses[0] -> { 
-    myObjectExample  myArrayOfObjects.aString+        "street": "Second Street"
 +        "zipCode""ZZ123" 
 +    }
 } }
 </code> </code>
- 
-===== Типы данных ===== 
- 
-  * Number / Numbers (dw::core::Numbers) 
-  * String / Strings (dw::core::Strings) 
-  * Boolean / Boolean (dw::Core Type) 
-  * Array / Arrays (dw::core::Arrays) 
-  * Object / Object (dw::Core Type) или {} 
  
 <code> <code>
Строка 1576: Строка 1197:
 output application/json output application/json
 --- ---
-+payload update 
-  /* +    case name at .user.@name -> upper(name)
-   * A multi-line +
-   * comment here. +
-   */ +
-  myString: "hello world", +
-  myNumber: 123, +
-  myFloatingPointNumber: 123.456, +
-  myVeryBigNumber: 12341234134123412341234123, +
-  myDate: |2018-12-07|, +
-  myTime: |11:55:56|, +
-  myDateTime: |2018-10-01T23:57:59-03:00|, +
-  myBoolean: true, +
-  myArray: [ 1, 2, 3, 5, 8], +
-  myMixedArray: [ 1, 2, "blah", { hello: "there" } ], +
-  myObjectKeyValuePair: { innerKey: "innerValue" }, +
-  myObjectWithConditionalField: { a : { b : 1, c : 2 if true, (d : 4) if false } }, +
-  myNull: null, +
-  myBinary: "abcd1234123" as Binary +
-  //A one-line comment here.+
 } }
 </code> </code>
Строка 1601: Строка 1204:
 <code> <code>
 %dw 2.0 %dw 2.0
- +var theFieldName = "name" 
-output json+output application/json
 --- ---
-typeOf({})+payload update { 
 +    case s at ."$(theFieldName)" -> "Shoki" 
 +}
 </code> </code>
- 
-===== Конвертирование массива в строку / join ===== 
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var payload = [1,2,3,4,5] 
 output application/json output application/json
 --- ---
-{ +payload map ((user) -> 
-    "a": payload joinBy ("-"+    user update { 
-}+        case name at .name if(name == "Ken") -> name ++ " (Leandro)" 
 +        case name at .name if(name == "Tomo"-> name ++ (Christian)" 
 +    } 
 +)
 </code> </code>
- 
-===== Конвертирование строки в массив / split ===== 
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var payload “a.b.c” +var myInput [{"lastName": "Doe"}, {"lastName": "Parker", "name": "Peter" }] 
-output application/java+output application/json
 --- ---
-payload splitBy(" ")+myInput  map ((value) -> 
 +    value update { 
 +        case name at .name! -> if(name == null) "JOHNelse upper(name) 
 +    } 
 +)
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var payload = “a.b.c” +output application/json
-output application/java+
 --- ---
-payload splitBy(".")+payload update { 
 +    //equivalent expression: 
 +    //case age at .age -> age + 1 
 +    case .age -> $ + 1 
 +    case .address.street -> "First Street" 
 +}
 </code> </code>
- 
-===== Итерация фиксированного количества циклов ===== 
  
 <code> <code>
 %dw 2.0 %dw 2.0
-var payload = { +var myInput = { 
- "totalcount": 5, +    "name": "Ken", 
- "employees": +    "lastName":"Shokida", 
-    +    "age": 30
-      { +
-        "name":"Sam", +
-        "age":34 +
-      }, +
-       { +
-        "name":"Richard", +
-        "age":38 +
-      }, +
-      { +
-        "name":"Harry", +
-        "age":36 +
-      }, +
-       { +
-        "name":"Tom", +
-        "age":40 +
-      }, +
-      { +
-        "name":"David", +
-        "age":84 +
-      }, +
-      { +
-        "name":"Chris", +
-        "age":52 +
-      } +
-    ]+
 } }
 output application/json output application/json
 --- ---
-(payload.employees  map (()->+myInput mapObject ((value,key) -> 
-FirstName: $.name, +    if(key as String == "age") 
-age: $.age +       {(key)value as Number + 1} 
-})) [ 0 to payload.totalcount -3 ]+    else 
 +       {(key): value} )
 </code> </code>
- 
-===== Преобразование JSON в CSV ===== 
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/csv quoteValues=true+var myInput = { 
 +    "name": "Ken", 
 +    "lastName":"Shokida", 
 +    "age": 30 
 +
 +output application/json
 --- ---
-payload+myInput update { 
 +    case age at .age -> age + 1 
 +}
 </code> </code>
  
 <code> <code>
 %dw 2.0 %dw 2.0
-output application/csv quoteValues=true,header=false+output application/json
 --- ---
-payload+payload map ((item) -> 
 +    item.ServiceDetails update { 
 +        case Designation at .Designation if (Designation == "Clerk") ->  "Assistant Manager" 
 +})
 </code> </code>
- 
-<code> 
-%dw 2.0 
-output application/csv quoteValues=true,header=true,separator="|" 
---- 
-payload 
-</code> 
- 
-===== Заголовок ===== 
- 
  
 ====== Ссылки ====== ====== Ссылки ======
  
   * https://docs.mulesoft.com/dataweave/latest/   * https://docs.mulesoft.com/dataweave/latest/
 +  * https://mulesy.com/1-mulesoft-as-middleware-solution/
 +  * https://reddeveloper.ru/tags/mule
 +  * https://questu.ru/tag/mule/