如果您有太多不同类型的对象导致无法尝试使用JSONEncoder方法或使用正则表达式处理,那么这里提供了一种后处理解决方案。此函数在指定的级别后折叠空格,而无需知道数据本身的具体细节。
def collapse_json(text, indent=12):
"""Compacts a string of json data by collapsing whitespace after the
specified indent level
NOTE: will not produce correct results when indent level is not a multiple
of the json indent level
"""
initial = " " * indent
out = []
sublevel = []
pending = None
for line in text.splitlines():
if line.startswith(initial):
if line[indent] == " ":
if pending:
sublevel.append(pending)
pending = None
item = line.strip()
sublevel.append(item)
if item.endswith(","):
sublevel.append(" ")
elif sublevel:
sublevel.append(line.strip())
out.append("".join(sublevel))
sublevel = []
else:
if pending:
out.append(pending)
pending = line.rstrip()
else:
if pending:
out.append(pending)
pending = None
if sublevel:
out.append("".join(sublevel))
out.append(line)
return "\n".join(out)
例如,使用此结构作为输入传递给json.dumps,缩进级别为4:
text = json.dumps({"zero": ["first", {"second": 2, "third": 3, "fourth": 4, "items": [[1,2,3,4], [5,6,7,8], 9, 10, [11, [12, [13, [14, 15]]]]]}]}, indent=4)
以下是不同缩进级别下该函数的输出:
>>> print collapse_json(text, indent=0)
{"zero": ["first", {"items": [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10, [11, [12, [13, [14, 15]]]]], "second": 2, "fourth": 4, "third": 3}]}
>>> print collapse_json(text, indent=4)
{
"zero": ["first", {"items": [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10, [11, [12, [13, [14, 15]]]]], "second": 2, "fourth": 4, "third": 3}]
}
>>> print collapse_json(text, indent=8)
{
"zero": [
"first",
{"items": [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10, [11, [12, [13, [14, 15]]]]], "second": 2, "fourth": 4, "third": 3}
]
}
>>> print collapse_json(text, indent=12)
{
"zero": [
"first",
{
"items": [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10, [11, [12, [13, [14, 15]]]]],
"second": 2,
"fourth": 4,
"third": 3
}
]
}
>>> print collapse_json(text, indent=16)
{
"zero": [
"first",
{
"items": [
[1, 2, 3, 4],
[5, 6, 7, 8],
9,
10,
[11, [12, [13, [14, 15]]]]
],
"second": 2,
"fourth": 4,
"third": 3
}
]
}
pprint
模块吗? - Bakuriujson.dumps(data_structure, indent=2)
- 将其作为示例添加进去。 - Rohaqsort_keys
等选项很好地配合使用,而且没有特殊情况的排序实现,而是依赖于(组合)collections.OrderedDict
。 - Erik Kaplun