Back to Examples

Record to EDI conversion

Same EDI schema and generated code used in EDI to record conversion example can be used to convert Ballerina records of type SimpleOrder to EDI.

{
    "name": "SimpleOrder",
    "delimiters" : {"segment" : "~", "field" : "*", "component": ":", "repetition": "^"},
    "segments" : [
        {
            "code": "HDR",
            "tag" : "header",
            "minOccurances": 1,
            "fields" : [{"tag": "code"}, {"tag" : "orderId", "required": true}, {"tag" : "organization"}, {"tag" : "date"}]
        },
        {
            "code": "ITM",
            "tag" : "items",
            "maxOccurances" : -1,
            "fields" : [{"tag": "code"}, {"tag" : "item", "required": true}, {"tag" : "quantity", "required": true, "dataType" : "int"}]
        }
    ]
}

Create a new Ballerina project named record_to_edi and create a module named sorder inside that project by using the below commands.

$ bal new record_to_edi
$ cd record_to_edi
$ bal add sorder

Create a new folder named resources in the root of the project and copy the schema file into it. At this point, directory structure of the project would look like below:

└── record_to_edi    ├── Ballerina.toml    ├── Dependencies.toml    ├── main.bal    ├── modules    │   └── sorder    │       ├── Module.md    │       ├── resources    │       ├── sorder.bal    │       └── tests    │           └── lib_test.bal    └── resources        └── simple_order_schema.json

Get the EDI tool from the Ballerina central using the below command:

$ bal tool pull edi

Run the below command from the project root directory to generate the Ballerina parser for the above schema.

$ bal edi codegen -i resources/simple_order_schema.json -o modules/sorder/sorder.bal

Note that it is recommended to place generated code for each EDI schema in a separate module in order to avoid conflicts.

Write a Ballerina program by using generated methods and records to convert Ballerina records to EDI.

import ballerina/io;
import record_to_edi.sorder;

public function main() returns error? {
    sorder:SimpleOrder simpleOrder = 
        {header: {code: "HDR", orderId: "ORDER_200", organization: "HMart", date: "17-05-2023"}};
    simpleOrder.items.push({code: "ITM", item: "A680", quantity: 15}); 
    simpleOrder.items.push({code: "ITM", item: "A530", quantity: 2}); 
    simpleOrder.items.push({code: "ITM", item: "A500", quantity: 4});
    string ediText = check sorder:toEdiString(simpleOrder);
    io:println(ediText);
}

Run the program using the command below:

$ bal runHDR*ORDER_200*HMart*17-05-2023~ITM*A680*15~ITM*A530*2~ITM*A500*4~
PreviousEDI to record conversion
NextEnvironment variables