漂亮的打印JSON转储

Bas*_*asj 19 python json dictionary dump python-2.x

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

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

输出:

{
  "a": "blah",
  "c": [
    1,
    2,
    3
  ],
  "b": "foo"
}
Run Code Online (Sandbox Code Playgroud)

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

我应该使用哪种语法...

{
  "a": "blah",
  "c": [1, 2, 3],
  "b": "foo"
}
Run Code Online (Sandbox Code Playgroud)

相反?

Sha*_*eru 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)
Run Code Online (Sandbox Code Playgroud)

输出:

{
   "a": "blah",
   "c": [1,2,3],
   "b": "foo"
}
Run Code Online (Sandbox Code Playgroud)

  • 你的序列化程序似乎工作得相当好,虽然它可能也应该将`None`s'转换为''null'. (3认同)
  • 真的有那么复杂吗?哇 (2认同)

All*_* Z. 6

我最终使用jsbeautifier

import jsbeautifier
opts = jsbeautifier.default_options()
opts.indent_size = 2
jsbeautifier.beautify(json.dumps(d), opts)
Run Code Online (Sandbox Code Playgroud)

输出:

{
  "a": "blah",
  "c": [1, 2, 3],
  "b": "foo"
}
Run Code Online (Sandbox Code Playgroud)


Bas*_*asj 6

多年后,我找到了一个带有内置pprint模块的解决方案:

import pprint
d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]}
pprint.pprint(d)                    # default width=80 so this will be printed in a single line
pprint.pprint(d, width=20)          # here it will be wrapped exactly as expected
Run Code Online (Sandbox Code Playgroud)

输出:

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

Run Code Online (Sandbox Code Playgroud)

  • 这不一定是有效的 JSON,这是一个打印精美的 Python 字典,通常也是有效的 JSON。 (3认同)

Mar*_*kHu 5

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

输出将是:

{"a": "blah",
"c": [1,
2,
3],
"b": "foo"}
Run Code Online (Sandbox Code Playgroud)

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