How can I create a record type dynamically? Is there any concept of reflection
or eval
in ballerina lang?
e.g.
// given this json type that we receive from a client
json j = [{"id": 1}, {"id":2}];
// how can I create a record and subsequently a table ?
It isn't possible to create record types dynamically. However, if your requirement is to just create a table from a JSON value, of which you do not know the member structure beforehand, you can use the value:fromJsonWithType
lang library function to construct the table specifying an appropriate open record (see the Open Records and Controlling openness examples) as the row type.
// Same as table<record {| anydata...; |}>
table<record {}> tb = check j.fromJsonWithType();
// If it is known to have an integer `id` field that needs to be used as the key.
// Same as table<record {| readonly int id; anydata...; |}>
table<record {readonly int id;}> key(id) tb2 = check j.fromJsonWithType();