简体   繁体   中英

How to extract the values from a Json Array in ballerina 0.982.0

I receive a query result from a database as [{"id":}]. When I try to capture this 'id' value as follows it returns a null.

 var getClientIdResult=eaDBEndpoint->select(QUERY_GET_CLIENT_ID,(),accountId); match getClientIdResult { table queryResult => { match <json>queryResult{ json jsonResult => { clientId=check<int> jsonResult["id"]; } error e => return e; } } error e => return e; } 

I suppose this cause because of the JSON result comes as a JSON array and the code does not capture the 'id' value inside the JSON object.

Any suggestions regarding how to capture the 'id' value will be helpful.

Since it is a JSON array, you have to access it with the index and then you can pick the element of the picked JSON with the key.

Example : This pick the initial JSON of the JSON array and get the id of it. jsonResult[0].id

var getClientIdResult = eaDBEndpoint->select(QUERY_GET_CLIENT_ID,(),accountId);
match getClientIdResult {
    table queryResult => {
        match <json>queryResult {
            json jsonResult => {
                clientId = check <int>jsonResult[0].id;
            }
            error e => return e;
        }
    }
    error e => return e;
}

Since it returns error if it occurred you can simply use check as follows:

var getClientIdResult = eaDBEndpoint->select(QUERY_GET_CLIENT_ID,(),accountId);
table queryResult = check <table>getClientIdResult;
json jsonResult = check <json>queryResult;
clientId = check <int>jsonResult[0].id;

Please refer [1] for more examples on how to use JSON arrays.

[1] https://ballerina.io/learn/by-example/json-arrays.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM