Search code examples
pythonjsonmultidimensional-arraypretty-print

Pretty print a JSON.dump 2d array in Python


I'm writing a python tile map editor. I was using a self designed code to write and parse some files but the code was very confusing, so I switched to JSON for simplicity.

My json file is hand made like this:

{ "Level" :

     {

    "levelName": "simpleLevel",

    "background":   [[12, 2,12, 2, 1, 2, 3, 3, 1, 1],
                     [ 1, 1, 7, 8, 5, 6, 7, 8,12, 3],
                     [ 1, 3, 1, 3,12,10,10, 1,12,12],
                     [ 2,12, 0, 4,10, 3,12, 2,12,12],
                     [12,12, 1, 1,10, 3,12, 2,12, 1],
                     [12,12,12, 0,10, 2, 1,12, 1,12],
                     [ 3,12, 3,12, 0, 2, 2,12,12, 3],
                     [ 1,12, 1,12, 1, 1,12,12, 3,12],
                     [ 3,12, 0,12,12,12,12,12, 3, 3],
                     [12, 3, 1, 2, 3,12,12,12, 1,12]],

    "foreground":   [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [ 0, 2, 0, 0, 0, 0, 0, 0, 0, 0],
                     [ 0, 3, 0, 0, 0, 0, 0, 0, 0, 0],
                     [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                     [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
    }
}

But, when I use json.dump(self.x, f) my output is in a single line, and when I try to use these parameter sort_keys=True, indent=4, separators=(',', ': ') I get a thousand linefeeds..

I just want something similar with my handmade file because it's easier to read and edit by hand. I could find some solutions to simple arrays but nothing that worked for 2d arrays. Is there a simple answer or should I code myself?

edit:

coded myself (with some help from the web..)

def fwriteKeyVals(data, f, indent=0):
    if isinstance(data, list):
        f.write( "\n" + "    " * indent + "[" )  
        for i in range(len(data) ):  
            if ( i == 0):
                f.write( "[" )  
            else:
                f.write( "    " * indent + " [" )
            for j in range(len(data[0])):  
                f.write( "%3d" % data[i][j] )  
                f.write( "," ) if j != len(data[0])-1 else (f.write( "]," ) if i != len(data)-1 else f.write( "]" ))  
            f.write( "\n" ) if i != len(data)-1 else f.write( "]" )  
    elif isinstance(data, dict):
        f.write( "\n" + "    " * indent + "{" )
        for k, v in data.iteritems():
            f.write( "\n" + "    " * indent + "\"" + k + "\"" + ": ")
            fwriteKeyVals(v, f, indent + 1)
            if( data.keys()[-1] != k):
                 f.write( "," )
        f.write( "\n" + "    " * indent + "}" )
    else:
        f.write("\"" + data + "\"")

Usage is:

fwriteKeyVals(x, f)

Where x = json.load(f) and f is the file I've loaded with f = open( map , "wb" ).


Solution

  • Ok, coded myself. Some hacks to print \n instead of real linefeed.

    def fwriteKeyVals(data, f, indent=0):
        if isinstance(data, list):
            try:
                gotdata = isinstance(data[0], list)
            except IndexError:
                gotdata = False
    
            if gotdata:
    
                f.write( "\n" + "    " * indent + "[" )  
                for i in range(len(data) ):  
                    if ( i == 0):
                        f.write( "[" )  
                    else:
                        f.write( "    " * indent + " [" )
                    for j in range(len(data[0])):  
                        f.write( "%3d" % data[i][j] )  
                        f.write( "," ) if j != len(data[0])-1 else (f.write( "]," ) if i != len(data)-1 else f.write( "]" ))  
                    f.write( "\n" ) if i != len(data)-1 else f.write( "]" )  
            else:
                try:
                    gotdata = data[0]
                except IndexError:
                    gotdata = 'False'
    
                if gotdata is not 'False':
                    f.write( " [" ) 
                    for i in range(len(data) ): 
                        if isinstance(data[i], Number):
                            f.write( "%3d" % data[i] )   
                        else:
                            dataListLf = data[i].split("\n")
                            dataToWrite = dataListLf[0]
                            for line in dataListLf[1:]:
                                dataToWrite += '\\n'+line
    
                            f.write( "\"" + dataToWrite + "\"")
                        f.write( "," ) if i != len(data)-1 else f.write( "]" )
                else:
                    f.write( " [\"\"]" )