Pretty Json

Pretty print a json object using proper indentation.

  • 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’

Example 1:

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

Example 2:

Input : ["foo", {"bar":["baz",null,1.0,2]}]
Output : 
[
    "foo", 
    {
        "bar":
        [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]

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

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

Your solution should return a list of strings, where each entry corresponds to a single line. The strings should not have “\n” character in them.

Interview Code Editor
Hints
  • Solution Approach
  • Complete Solution
2114 successful submissions.
Asked In:
  • Facebook
  • Microsoft
Click here to jump start your coding interview preparation