如何用DataWeave 1.0处理嵌套JSON数组内的指定日期属性转换
Solution for Nested Date Format Transformation in DataWeave 1.0
Got it, let's fix this! Your current code handles objects nicely but misses arrays entirely—since your payload has nested arrays containing objects with date fields, we need to extend the recursive function to account for array types and process every element inside them.
Updated DataWeave Code
%dw 1.0 %output application/json %var keysToUpdate = ['datefield_1', 'datefield_2', 'datefield_3', 'datefield_4', 'datefield_5', 'datefield_6', 'datefield_7'] %function transformDateFormat(inputDate) inputDate as :date {format: "dd/MM/yyyy"} as :date {format: "yyyy-MM-dd"} %function findKey(key) keysToUpdate contains key %function changePayload(input) input map changePayload($) when input is :array else input mapObject ({ ($$): changePayload($) when $ is :object otherwise $ } unless findKey($$ as :string) otherwise { ($$): transformDateFormat($) }) --- changePayload(payload)
Key Changes Explained
- Array Handling: We added a check at the start of
changePayloadto detect if the input is an array. If it is, we usemapto iterate over every element in the array and applychangePayloadrecursively to each one. This works for any level of nested arrays (like yourarrayList1andarrayList2). - Full Recursive Traversal: The function now properly navigates all structures in your payload:
- Top-level key-value pairs
- Objects nested inside other objects
- Arrays at any depth
- Objects nested inside arrays (and arrays inside those objects)
- Reusable Helpers: Your existing
transformDateFormatandfindKeyfunctions stay exactly as they are—we just extended the main processing logic to cover array scenarios.
Result
For your input payload, every date field matching the keysToUpdate list (even the deeply nested ones like datefield_5 and datefield_6) will be converted from dd/MM/yyyy to yyyy-MM-dd format, while all other keys and values remain unchanged.
内容的提问来源于stack exchange,提问作者Spottsworth
相关产品推荐
相关产品推荐

