使用制表符缩进(不是空格)转储JSON

2024-06-25 23:28:58 发布

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

我知道如何使用空格转储JSON字符串。这是我当前用于美化和转储JSON字符串的命令:

json.dump(data, open('dev_integrated.json', 'w'), sort_keys=True, indent=4, separators=(',', ': '))

我想知道是否有方法指定缩进1个制表符而不是4个空格。我没能在任何地方的文件里查到。

谢谢。


Tags: 字符串dev命令jsontruedataopenkeys
1条回答
网友
1楼 · 发布于 2024-06-25 23:28:58

对于Python2.7,有一个使用正则表达式的解决方法:

import re
dump = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
#Replaces spaces with tab
new_data = re.sub('\n +', lambda match: '\n' + '\t' * (len(match.group().strip('\n')) / 3), dump)
json.dump(new_data, open('dev_integrated.json', 'w')

这是针对Python 3.2+

从文档中:

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.

json.dump(jString, open('dev_integrated.json', 'w'), sort_keys=True, indent='\t', separators=(',', ': '))

相关问题 更多 >