漂亮的打印JSON转储

2024-05-19 17:39:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用此代码将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"
}

而不是?


Tags: 代码import功能json元素列表foo语法
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"
}

编写自己的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"
}

另一种选择是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的官方文档中说默认参数是separators=None——这实际上意味着“使用separators=(', ',': ')的默认值”。还要注意,逗号分隔符不区分k/v对和list元素。

相关问题 更多 >