import ballerina/io;
type Person {
string name;
int age;
string city;
};function main (string[] args) {
json<Person> person = {name:"Jon"};
person.age = 25;
person.city = "Colombo";
io:println(person);
json employee = person;
employee.profession = "Software Engineer";
io:println(employee);
}
Constrained JSONA JSON can be constrained with a struct definition to restrict the fields of the JSON to that of the struct. If you try to access a field with an invalid field as per the struct definition or initialize a JSON with invalid fields, this will cause a compilation error. Restricting the fields of the JSON will enforce the format of the JSON variable. |
|
import ballerina/io;
|
|
type Person {
string name;
int age;
string city;
};
|
Defining Person type. |
function main (string[] args) {
|
|
json<Person> person = {name:"Jon"};
|
Create a new JSON that is constrained by the Person struct. Only the fields defined in the Person struct can be accessed. If we try to access a non existing field, it will produce a compilation error. |
person.age = 25;
person.city = "Colombo";
io:println(person);
|
We can access fields defined in the Person struct without any issue. |
json employee = person;
|
We can assign this constrained JSON to a JSON. This will allow us to add new elements that are not in the struct. |
employee.profession = "Software Engineer";
io:println(employee);
}
|
After that, we can add new elements to the JSON. |
$ ballerina run constrained-json.bal
{"name":"Jon","age":25,"city":"Colombo"}
{"name":"Jon","age":25,"city":"Colombo","profession":"Software Engineer"}
|
|