Search code examples
jsonballerina

Converting a Ballerina record with an error field to json


How can I convert the record given below to a json value?

type PaymentEvent record {
    string orderId;
    string message;
    string occurredAt = time:utcToString(time:utcNow());
    anydata|error payload?;
};

Solution

  • You can use toJson() langlib function to convert any anydata value to json.

    But, that is not possible here since the payload field allows an error value, which does not belong to json. So you would have to explicitly map to json or convert to some intermediate record without the error and then use toJson() (but that would add an additional conversion).

    import ballerina/time;
    
    type PaymentEvent record {
        string orderId;
        string message;
        string occurredAt = time:utcToString(time:utcNow());
        anydata|error payload?;
    };
    
    function convert(PaymentEvent event) returns map<json> {
        map<json> eventJson = {
            orderId: event.orderId,
            message: event.message,
            occurredAt: event.occurredAt
        };
    
        if event.hasKey("payload") {
            anydata|error payload = event?.payload;
    
            if payload is error {
                // handle the scenario where the payload is an error
            } else {
                eventJson["payload"] = payload.toJson();
            }
        }
    
        return eventJson;
    }