[英]Dumps Not Write To JSON file Pretty Print I Already using "indent=4" I added JSON View
[英]Pretty print JSON dumps
我使用此代码将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"
}
反而?
我最终使用了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 对和列表元素。
多年后,我找到了内置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
输出:
{'a': 'blah',
'b': 'foo',
'c': [1, 2, 3]}
我无法让 jsbeautifier 做很多事情,所以我使用了正则表达式。 有 json 模式,如
'{\n "string": [\n 4,\n 1.0,\n 6,\n 1.0,\n 8,\n 1.0,\n 9,\n 1.0\n ],\n...'
我想要的
'{\n "string": [ 4, 1.0, 6, 1.0, 8, 1.0, 9, 1.0],\n'
所以
t = json.dumps(apriori, indent=4)
t = re.sub('\[\n {7}', '[', t)
t = re.sub('(?<!\]),\n {7}', ',', t)
t = re.sub('\n {4}\]', ']', t)
outfile.write(t)
因此,我有这 5 行,而不是一个“dump(apriori, t, indent=4)”。
这也困扰了我一段时间,我发现了一个我几乎满意的 1 班轮:
print json.dumps(eval(str(d).replace('[', '"[').replace(']', ']"').replace('(', '"(').replace(')', ')"')), indent=2).replace('\"\\"[', '[').replace(']\\"\"', ']').replace('\"\\"(', '(').replace(')\\"\"', ')')
这基本上将所有列表或元组转换为字符串,然后使用带有缩进的 json.dumps 来格式化字典。 然后你只需要删除引号就完成了!
注意:无论 dict 是如何嵌套的,我都将 dict 转换为字符串以轻松转换所有列表/元组。
附注。 我希望 Python 警察不会因为我使用 eval 来找我...(小心使用)
也许效率不高,但考虑一个更简单的情况(在 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,但是您可以添加参数并传递它们,或者对您自己的进行硬编码等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.