import ballerina/io;
type Person {
    string name;
    int age;
    string city;
};
transformer <Person p, json<Person> j> updateCity(string city) {
    j.name = p.name;
    j.age = p.age;
    j.city = city;
}function main (string[] args) {
    json j = {"name":"Ann", "age":30, "city":"New York"};
    Person p = {};
    var value = <Person>j;    match value {
        Person pe => p = pe;
        error err => {
            io:println(err);
        }
    }
    string city = "London";
    json<Person> response =? <json<Person>, updateCity(city)>p;    io:println(response);
}

Transform JSON

Transformers are used to convert a variable of one type to another. This sample is about defining and using a custom transformer to convert struct variable to an output 'json' variable which is constraint by a struct type.

import ballerina/io;
type Person {
    string name;
    int age;
    string city;
};

Defining Person struct.

transformer <Person p, json<Person> j> updateCity(string city) {
    j.name = p.name;
    j.age = p.age;
    j.city = city;
}

Defining transformer to convert from Person type to constrained JSON.

function main (string[] args) {
    json j = {"name":"Ann", "age":30, "city":"New York"};
    Person p = {};

Declare a Person variable.

    var value = <Person>j;

Convert JSON to a Person type variable.

    match value {
        Person pe => p = pe;
        error err => {
            io:println(err);
        }
    }

Print if an error is thrown.

    string city = "London";

Define a constant city value as “London”.

    json<Person> response =? <json<Person>, updateCity(city)>p;

Convert p of type Person to the response JSON, using the transformer defined earlier.

    io:println(response);
}
$ ballerina run transform-json.bal
{"name":"Ann","age":30,"city":"London"}