python JSON array newlines

后端 未结 3 1374
春和景丽
春和景丽 2021-02-19 22:41

I have a large dictionary that has some large array data in it:

d = {\'something\': {\'else\': \'x\'}, \'longnumbers\': [1,2,3,4,54,6,67,7,7,8,8,8,6,4,3,3,5,6,7,         


        
3条回答
  •  臣服心动
    2021-02-19 23:41

    I ended up just writing my own JSON serializer:

    import numpy
    
    INDENT = 3
    SPACE = " "
    NEWLINE = "\n"
    
    def to_json(o, level=0):
        ret = ""
        if isinstance(o, dict):
            ret += "{" + NEWLINE
            comma = ""
            for k,v in o.iteritems():
                ret += comma
                comma = ",\n"
                ret += SPACE * INDENT * (level+1)
                ret += '"' + str(k) + '":' + SPACE
                ret += to_json(v, level + 1)
    
            ret += NEWLINE + SPACE * INDENT * level + "}"
        elif isinstance(o, basestring):
            ret += '"' + o + '"'
        elif isinstance(o, list):
            ret += "[" + ",".join([to_json(e, level+1) for e in o]) + "]"
        elif isinstance(o, bool):
            ret += "true" if o else "false"
        elif isinstance(o, int):
            ret += str(o)
        elif isinstance(o, float):
            ret += '%.7g' % o
        elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.integer):
            ret += "[" + ','.join(map(str, o.flatten().tolist())) + "]"
        elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.inexact):
            ret += "[" + ','.join(map(lambda x: '%.7g' % x, o.flatten().tolist())) + "]"
        elif o is None:
            ret += 'null'
        else:
            raise TypeError("Unknown type '%s' for json serialization" % str(type(o)))
        return ret
    

提交回复
热议问题