漂亮的打印JSON转储

问题描述 投票:15回答:5

我使用这段代码将dict打印成JSON:

import json
d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]}
print json.dumps(d, indent = 2, separators=(',', ': '))

输出:

{
  "a": "blah",
  "c": [
    1,
    2,
    3
  ],
  "b": "foo"
}

这有点太多了(每个列表元素的换行符!)。

我应该使用哪种语法来实现此目的:

{
  "a": "blah",
  "c": [1, 2, 3],
  "b": "foo"
}

代替?

python json dictionary python-2.x dump
5个回答
7
投票

编写自己的JSON序列化程序:

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())) + "]"
    else:
        raise TypeError("Unknown type '%s' for json serialization" % str(type(o)))
    return ret

inputJson = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]}
print to_json(inputJson)

输出:

{
   "a": "blah",
   "c": [1,2,3],
   "b": "foo"
}

3
投票

另一种选择是print json.dumps(d, indent = None, separators=(',\n', ': '))

输出将是:

{"a": "blah",
"c": [1,
2,
3],
"b": "foo"}

请注意,虽然https://docs.python.org/2.7/library/json.html#basic-usage的官方文档说默认args是separators=None - 实际上意味着“使用separators=(', ',': ')的默认值”。请注意,逗号分隔符不区分k / v对和列表元素。


3
投票

我最终使用jsbeautifier

import jsbeautifier
opts = jsbeautifier.default_options()
opts.indent_size = 2
jsbeautifier.beautify(json.dumps(d), opts)

输出:

{
  "a": "blah",
  "c": [1, 2, 3],
  "b": "foo"
}

0
投票

也许效率不高,但考虑一个更简单的情况(在Python 3中进行过一些测试,但也可能在Python 2中有效):

def dictJSONdumps( obj, levels, indentlevels = 0 ):
    import json
    if isinstance( obj, dict ):
        res = []
        for ix in sorted( obj, key=lambda x: str( x )):
            temp = ' ' * indentlevels + json.dumps( ix, ensure_ascii=False ) + ': '
            if levels:
                temp += dictJSONdumps( obj[ ix ], levels-1, indentlevels+1 )
            else:
                temp += json.dumps( obj[ ix ], ensure_ascii=False )
            res.append( temp )
        return '{\n' + ',\n'.join( res ) + '\n}'
    else:
        return json.dumps( obj, ensure_ascii=False )

除了完全编写自己的序列化程序之外,这可能会给你一些想法。我使用了自己喜欢的缩进技术和硬编码的ensure_ascii,但是你可以添加参数并传递它们,或者硬编码你自己的等等。


0
投票

这一直困扰我一段时间,我找到了一个我很满意的1班轮:

print json.dumps(eval(str(d).replace('[', '"[').replace(']', ']"').replace('(', '"(').replace(')', ')"')), indent=2).replace('\"\\"[', '[').replace(']\\"\"', ']').replace('\"\\"(', '(').replace(')\\"\"', ')')

这基本上将所有列表或元组转换为字符串,然后使用带缩进的json.dumps来格式化字典。然后你只需要删除引号和你的完成!

注意:我将dict转换为字符串,以便轻松转换所有列表/元组,无论dict是如何嵌套的。

PS。我希望Python警察不会跟我使用eval ...(小心使用)

© www.soinside.com 2019 - 2024. All rights reserved.