python JSON数组换行符 [英] python JSON array newlines
问题描述
我有一个很大的字典,里面有一些大数组数据:
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,4,3,5,6,54]}
真正的字典具有更多的键和嵌套结构.当我在不使用indent
的情况下使用json.dump
时,会得到一个紧凑的单行输出,该输出不可读.设置indent
时,它将在每个分隔符(包括数组)之后放置换行符.
The real dictionary has many more keys and a nested structure. When I use json.dump
without indent
, I get a compact, single-line output which is not readable. When I set indent
, it puts newlines after every separator, including the arrays.
数字数组很长,最终像这样:
The numerical arrays are long and end up like this:
"longnumbers": [
1,
2,
3,
4,
54,
6,
67,
7,
7,
8,
8,
8,
6,
4,
3,
3,
5,
6,
7,
4,
3,
5,
6,
54
],
有没有办法获得带有缩进级别的精美印刷的JSON,但没有在数组元素后放置换行符?对于上面的示例,我想要这样的东西:
Is there any way to get pretty-printed JSON with an indent level, but without placing newlines after array elements? For the example above, I'd like something like this:
{
"longnumbers": [1, 2, 3, 4, 54, 6, 67, 7, 7, 8, 8, 8, 6, 4, 3, 3, 5, 6, 7, 4, 3, 5, 6, 54],
"something": {
"else": "x"
}
}
推荐答案
我最终只是编写了自己的JSON序列化程序:
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
这篇关于python JSON数组换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!