迭代 JSON 映射并获取 Ballerina 中的键值对

问题描述 投票:0回答:1

我有以下 JSON:

json envs = {
    "user": "user",
    "pass": "password",
    "key": "key1"
};  

有没有办法在 Ballerina 中迭代这个 JSON 映射并获取键值对?

json iteration ballerina
1个回答
0
投票

我们可以将类型缩小为

map<json>
,然后使用
ballerina/lang.map
langlib 中的函数或地图上可用的任何其他操作(例如,使用
foreach
进行迭代)。检查以下代码:

public function main() returns error? {
    // Similar to a cast, but returns an error instead of
    // panicking if incompatible.
    map<json> envsMap = check envs.ensureType();

    foreach [string, json] [key, value] in envsMap.entries() {
        // Handle the values here.
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.