Solution for Pretty JSON

programming
Tags: #<Tag:0x00007f242646b5a8>

#1
vector<string> Solution::prettyJSON(string A) {
    int level = 0;
    if(*A.begin() == '\"'){
        A.erase(A.begin());
    }
    
    if(*A.end() == '\"'){
        A.erase(--A.end());
    }
    
    vector<string> ans;
    
    string s = "";
    int n = A.size();
    
    for(int i = 0; i < n; i++){
        if(A[i] == '{' || A[i] == '[') {
            if(s.size() > 0){
                string space(level, '\t');
                space+= s;
                ans.push_back(space);
                s = "";
            }
            string open(level, '\t');
            open+= A[i];
            ans.push_back(open);
            level++;
        }else if(A[i] == '}' || A[i] == ']') {
            if(s.size() > 0){
                string space(level, '\t');
                space+= s;
                ans.push_back(space);
                s = "";
            }
            level--;
            string open(level, '\t');
            open+= A[i];
            if(i+1 < n && A[i+1] == ','){
                open+=A[i+1];
                i++;
            }
            ans.push_back(open);
            
        }else if(A[i] == ','){
            string space(level, '\t');
            space+= s+",";
            ans.push_back(space);
            s = "";
        }else{
            s+= A[i];
        }      
    }

    return ans;    
}