I'm getting a JSON from [1], due to the naming of the keys in the json I was unable to straightaway use either of the 2 approches in hadling JSON in ballerina:
Approach 1: Work with json values directly:
string s = check j.x.y.z;
Approach 2: Work with application-specific, user-defined subtype of anydata:
couldn't use cloneWithType or directly assign to a user defined record type
My workaround was:
type AllStockData record {
string open;
string high;
string low;
string close;
string volume;
};
AllStockData[] stockData = [];
public function main() returns @tainted error? {
http:Client httpClient = check new ("https://www.alphavantage.co");
json jsonPayload = check httpClient->get("/query?function=TIME_SERIES_INTRADAY&symbol="+searchSymbol.toUpperAscii()+"&interval=5min&apikey="+apiKey, targetType = json);
map<json> allData = <map<json>>jsonPayload;
foreach json item in <map<json>>allData["Time Series (5min)"] {
map<json> stockItem = <map<json>>item;
AllStockData stock = {
open: stockItem["1. open"].toString(),
high: stockItem["2. high"].toString(),
low: stockItem["3. low"].toString(),
close: stockItem["4. close"].toString(),
volume: stockItem["5. volume"].toString()
};
stockData.push(stock);
}
I was wondering If there is a better way to do this?