Using json.dump() with Python 2, indent argument is limited to number of spaces only - no ability for tabs use.
Class JSONTabIndentFileWriter provides a file-like object which will rewrite json.dump() output indending from spaces to tabs.
Using json.dump() with Python 2, indent argument is limited to number of spaces only - no ability for tabs use.
Class JSONTabIndentFileWriter provides a file-like object which will rewrite json.dump() output indending from spaces to tabs.
| import json | |
| import re | |
| TEST_DICTIONARY = { | |
| 'key1': 'value1', | |
| 'key2': ['one','two','three','four'], | |
| 'key3': { | |
| 'apple': 'orange', | |
| 'grape': 'banana', | |
| 'tomato': ['five','six','seven','eight'] | |
| } | |
| } | |
| JSON_SPACE_INDENT_COUNT = 4 | |
| class JSONTabIndentFileWriter: | |
| def __init__(self,filepath,indent): | |
| # open JSON file | |
| self.fh = open(filepath,'w') | |
| # create indent find regular expression | |
| self.indent_regexp = re.compile(r'^([\[,]*\r?\n)( {{{0},}})(.*)'.format(indent)) | |
| self.indent_size = indent | |
| def write(self,output): | |
| # match JSON builder indent output | |
| indent_match = self.indent_regexp.search(output) | |
| if (indent_match): | |
| # swap out space indents with tabs | |
| output = ''.join([ | |
| indent_match.group(1), # optional "[" or "," character before indent | |
| '\t' * int(len(indent_match.group(2)) / self.indent_size), # indent conversion | |
| indent_match.group(3) # characters past indent | |
| ]) | |
| # write output to file | |
| self.fh.write(output) | |
| def close(self): | |
| self.fh.close() | |
| def main(): | |
| # create JSON tab indent file writer | |
| json_tab_file_write = JSONTabIndentFileWriter( | |
| 'outfile.json', | |
| JSON_SPACE_INDENT_COUNT | |
| ) | |
| # dump TEST_DICTIONARY to JSON with tab indenting | |
| json.dump( | |
| TEST_DICTIONARY, | |
| json_tab_file_write, | |
| indent = JSON_SPACE_INDENT_COUNT, | |
| separators = (',',': '), | |
| sort_keys = True | |
| ) | |
| # close file writer | |
| json_tab_file_write.close() | |
| if (__name__ == '__main__'): | |
| main() |