skip to Main Content
json data = {"vals": ["a", "b", "c"]};

How to iterate above JSON and get a,b,c?

2

Answers


  1. Chosen as BEST ANSWER
    public function main() returns error? {
        json data = {"vals": ["a", "b", "c"]};
    
        json vals = check data.vals;
        json[] arr = check vals.ensureType();
    
        //// or just
        // json[] arr = check data.vals.ensureType(); 
        
        foreach json item in arr {
            
        }
    }
    

    We need to narrow the type down to an iterable type after accessing the field as shown above.


  2. You can use the following approach if you are unsure of the JSON field name in advance.

    public function main() {
        json data = {"vals": ["a", "b", "c"]};
        if data !is map<json> {
            return;
        }
        foreach [string, json] [fieldName, value] in data.entries() {
            if value is json[] {
                io:println("Field Name : ", fieldName);
                io:print("Array Values : ");
                iterateJsonArray(value);
            }
        }
    }
    
    function iterateJsonArray(json[] arr) {
        foreach json member in arr {
            io:print(member, " ");
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search