Search code examples
mulefixed-widthanypoint-studiodataweave

How do I map a complex object to DataWeave fixed width format


I have a JSON Object

{
   "collection": [
      { 
         "field1": "1111",
         "field2": "1122"
      },
      { 
         "field1": "2211",
         "field2": "2222"
      }
   ],
   "otherObject": {
      "otherField": "3333"
   }
}

I would like to have this output :

s01>1111~~~~~~1122~~~~~~

s01>2211~~~~~~2222~~~~~~

s02>3333~~~~~~

So i used this transformation :

%dw 1.0
%output text/plain structureIdent = "response" , schemaPath = "response.ffd"

---
{
    collection: payload.collection map ({
        field1: $.field1,
        field2: $.field2
    }),
    otherObject: {
        otherField: payload.otherObject.otherField
    }
}

and my response.ffd is like this

  form: FIXEDWIDTH
  structures:
  - id: 'response'
    name: response
    tagStart: 0
    data:
    - { idRef: 'collection', count: '>1'}
    - { idRef: 'otherObject', count: 1 }
  segments:
  - id: 'collection'
    name: collection
    tag: 's01>'
    values:
    - { name: 'field1', type: String, length: 10 }
    - { name: 'field2', type: String, length: 10 }
  - id: 'otherObject'
    name: otherObject
    tag: 's02>'
    values:
    - { name: 'otherField', type: String, length: 10 }

But i'm getting this result

s02>3333~~~~~~

as if dataweave doesn't know about my array, What should i do to get it working?


Solution

  • Modify the DataWeave code with the following example:

    %dw 1.0
    %output text/plain structureIdent = "response" , schemaPath = "response.ffd"
    ---
    {
        collection: flatten [payload.collection map ({
            field1: $.field1,
            field2: $.field2
        })],
        otherObject: {
            otherField: payload.otherObject.otherField
        }
    }
    
    1. Ensure the collection is an Array by adding a bracket: [ ... map ...]
    2. Remove the additional bracket using flatten, because the map itself already return an Array

    Although it returns the same result, somehow DataWeave treats it differently as if the data structure is written manually: e.g.:

    collection: [{
        field1: payload.collection.field1[0],
        field2: payload.collection.field2[0]
    },{
        field1: payload.collection.field1[1],
        field2: payload.collection.field2[1]
    }]