漂亮在Python中打印JSON.dump 2d数组

时间:2014-08-08 01:29:32

标签: python json multidimensional-array pretty-print

我正在编写一个python tile map编辑器。我使用自行设计的代码来编写和解析一些文件,但代码非常混乱,所以我为了简单起见切换到了JSON。

我的json文件是这样手工制作的:

{ "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]]
    }
}

但是,当我使用json.dump(self.x, f)时,我的输出就在一行中,当我尝试使用这些参数sort_keys=True, indent=4, separators=(',', ': ')时,我会得到一千个换行符。

我只想要与我的手工文件类似的东西,因为它更容易手工阅读和编辑。我可以找到一些简单数组的解决方案,但没有任何适用于2d数组。有一个简单的答案还是我应该自己编码?

编辑:

自己编码(在网上提供一些帮助......)

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 + "\"")

用法是:

fwriteKeyVals(x, f)

x = json.load(f)f是我加载f = open( map , "wb" )的文件。

2 个答案:

答案 0 :(得分:2)

你应该看看pprint,一个用于Python数据结构的Python模块。以下代码应该为您提供所需的打印:

# x -> your json dict
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(x)

答案 1 :(得分:0)

好的,自己编码。有些黑客打印\ n而不是真正的换行。

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( " [\"\"]" )