import ballerina/io;function main (string[] args) {
json empty = {}; int age = 30;
json p = {fname:"John", lname:"Stallone", "age":age};
io:println(p);
json firstName = p.fname;
io:println(firstName);
json lastName = p["lname"];
io:println(lastName);
p.lname = "Silva";
p["age"] = 31;
io:println(p);
json p2 = {
fname:"Peter",
lname:"Stallone",
"age":age,
address:{
line:"20 Palm Grove",
city:"Colombo 03",
country:"Sri Lanka"
}
};
io:println(p2); p2.address.province = "Western";
io:println(p2);
}
JSON LiteralsJSON literals are written exactly the same way as Ballerina structs and maps. |
|
import ballerina/io;
|
|
function main (string[] args) {
|
|
json empty = {};
|
Creates an empty JSON Object. |
int age = 30;
|
|
json p = {fname:"John", lname:"Stallone", "age":age};
io:println(p);
|
Create a JSON object. Keys can be defined with or without quotes. Values can be any expression. |
json firstName = p.fname;
io:println(firstName);
|
You can access the object values by using dot (.) notation or array index notation. |
json lastName = p["lname"];
io:println(lastName);
|
Array index notation allows you use any string valued expression as the index. |
p.lname = "Silva";
p["age"] = 31;
io:println(p);
|
Add or change object values. |
json p2 = {
fname:"Peter",
lname:"Stallone",
"age":age,
address:{
line:"20 Palm Grove",
city:"Colombo 03",
country:"Sri Lanka"
}
};
io:println(p2);
|
Nested JSON objects. |
p2.address.province = "Western";
io:println(p2);
}
|
|
$ ballerina run json-literals.bal
{"fname":"John","lname":"Stallone","age":30}
John
Stallone
{"fname":"John","lname":"Silva","age":31}
{"fname":"Peter","lname":"Stallone","age":30,
"address":{"line":"20 Palm Grove","city":"Colombo 03","country":"Sri Lanka"}}
{"fname":"Peter","lname":"Stallone","age":30,
"address":{"line":"20 Palm Grove","city":"Colombo 03",
"country":"Sri Lanka","province":"Western"}}
|
At the command line, navigate to the directory that contains the
|