Skip to content

Instantly share code, notes, and snippets.

@ballerina-github-bot
Created November 23, 2023 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ballerina-github-bot/754f4fa2b93764d9e1891080e2c3aee5 to your computer and use it in GitHub Desktop.
Save ballerina-github-bot/754f4fa2b93764d9e1891080e2c3aee5 to your computer and use it in GitHub Desktop.
Ballerina Playground
import ballerina/io;
type Student record {|
int id;
string name;
|};
public function main() returns error? {
// As JSON is a union: `()|boolean|int|float|decimal|string|json[]|map<json>`,
// the following cases are allowed.
json n = null;
json i = 21;
json s = "str";
json a = [1, 2];
json m = {"x": n, "y": s, "z": a};
io:println(m);
json[] arr = [m, {"x": i}];
io:println(arr);
string rawData = "{\"id\": 2, \"name\": \"Georgy\"}";
// Get the `json` value from the string.
json j = check rawData.fromJsonString();
io:println(j);
// Access the fields of `j` using field access.
string name = check j.name;
io:println(name);
// Convert the `json` into a user-defined type.
Student student = check j.cloneWithType();
io:println(student.id);
// Convert the user-defined type to a `json`.
j = student;
io:println(j);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment