Pretty Json

Given a string A representating json object. Return an array of string denoting json object with proper indentaion.

Rules for proper indentaion:

  • Every inner brace should increase one indentation to the following lines.

  • Every close brace should decrease one indentation to the same line and the following lines.

  • The indents can be increased with an additional ‘\t’

Note:

  1. [] and {} are only acceptable braces in this case.

  2. Assume for this problem that space characters can be done away with.

Input Format

The only argument given is the integer array A.

Output Format

Return a list of strings, where each entry corresponds to a single line. The strings should not have "\n" character in them.

For Example

Input 1:
    A = "{A:"B",C:{D:"E",F:{G:"H",I:"J"}}}"
Output 1:
    { 
        A:"B",
        C: 
        { 
            D:"E",
            F: 
            { 
                G:"H",
                I:"J"
            } 
        } 
    }

Input 2:
    A = ["foo", {"bar":["baz",null,1.0,2]}]
Output 2:
   [
        "foo", 
        {
            "bar":
            [
                "baz", 
                null, 
                1.0, 
                2
            ]
        }
    ]
public class Solution {
    public boolean isBracket(char c) {
        if (c == '[' || c == '{' || c == '}' || c == ']')
            return true;
        else
            return false;
    }

    public ArrayList<String> prettyJSON(String A) {
        int tabLevel = 0;
        ArrayList<String> ans = new ArrayList<>();
        for (int i = 0; i < A.length();) {
            if (A.charAt(i) == ' ')
                i++;
            StringBuilder tabs = new StringBuilder();
            for (int j = 1; j <= tabLevel; j++)
                tabs.append("\t");
            if (isBracket(A.charAt(i))) {
                String temp = tabs.toString() + A.charAt(i);
                if (A.charAt(i) == '}' || A.charAt(i) == ']')
                    temp = temp.substring(1); // reduces 1 tab level in string
                if (i + 1 < A.length() && A.charAt(i + 1) == ',') {
                    temp += A.charAt(i + 1);
                    i++;
                }
                ans.add(temp);
                if (A.charAt(i) == '{' || A.charAt(i) == '[')
                    tabLevel++;
                else
                    tabLevel--;
                i++;
            } else {
                int temp = i;
                StringBuilder str = new StringBuilder();
                while (temp < A.length() && !isBracket(A.charAt(temp))) {
                    str.append(A.charAt(temp));
                    if (A.charAt(temp) == ',') {
                        temp++;
                        break;
                    }
                    temp++;
                }
                ans.add(tabs.toString() + str.toString());
                i = temp;
            }
        }
        return ans;
    }
}

Last updated