Back to Examples

Access JSON elements

Ballerina defines certain types as lax types for which static typing rules are less strict. json is defined to be a lax type along with any map<T> where T is a lax type.

For example, field access (.) and optional field access (?.), which are generally allowed on records and objects for fields that are defined in the type descriptors, are also allowed additionally on lax types. For such operations, some of the type checkings are moved from compile time to runtime.

The best way of accessing JSON elements is to convert the json value to a user-defined type.

check Expr is treated as check val:ensureType(Expr, s) when the Expr is a subtype of JSON and the expected type is a subtype of ()|boolean|int|float|decimal|string. s is a typedesc value representing the expected type.

import ballerina/io;
import ballerina/lang.value;
 
public function main() returns error? {
    json[] users = [
        {
            user: {
                name: {
                    firstName: "John",
                    lastname: "Smith"
                },
                age: 24
            }
        },
        null
    ];

    // Field access is allowed on the `json` typed variable. However, the return
    // type would be a union of `json` and `error`.
    json firstUserName = check users[0].user.name;
    
    // This is converted to `check value:ensureType(firstUserName.firstName, string)`.
    // As the expected type is correct, the conversion is successful.
    string firstName = check firstUserName.firstName;
    io:println("Value of first name: " + firstName);
    
    // This is same as above.
    firstName = check value:ensureType(firstUserName.firstName, string);
    io:println("Value of first name: " + firstName);
}

Run the example as follows.

$ bal run access_json_elements.balValue of first name: JohnValue of first name: John

Related links

PreviousJSON type
NextAccess optional JSON elements