Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dumping a JSON using tab indents (not spaces)

I know how to dump a JSON string using spaces. This is the command I'm currently using to prettify and dump a JSON string:

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

I wanted to know if there was a way to specify indent of 1 tab instead of 4 spaces. I wasn't able to look this up in the docs anywhere.

Thanks.

like image 349
cs95 Avatar asked Jun 29 '17 08:06

cs95


1 Answers

Python 2.7

there is a workaround that can be implemented using regular expressions :

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+

From the Docs :

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.

Hence the TAB-indentation can be implemented as follows:

json.dump(jString, open('dev_integrated.json', 'w'), sort_keys=True, indent='\t', separators=(',', ': '))
like image 95
Stack Avatar answered Oct 21 '22 14:10

Stack