json,dict数据写入自动排版

import json

with open('config.json') as f:
    result = json.loads(f.read())

with open('testconfig.json', 'wb') as f:
    space_count = 0
    last_char = ''
    current = ''
    is_in_double_quote = False
    for current_char in json.dumps(result):
        last_char = current
        current = current_char
        if is_in_double_quote:
            if current_char == '"':
                if last_char == "\\":
                    f.write(current_char)
                else:
                    is_in_double_quote = not is_in_double_quote
                    f.write(current_char)
            else:
                f.write(current_char)
        else:
            if current_char == '"':
                is_in_double_quote = not is_in_double_quote
                f.write(current_char)
            elif current_char == '{':
                space_count += 1
                j = 0
                current_char += '\n'
                while j < space_count:
                    current_char += '    '
                    j += 1
                f.write(current_char)
            elif current_char == '}':
                space_count -= 1
                j = 0
                add_space = '\n'
                while j < space_count:
                    add_space += '    '
                    j += 1
                current_char = add_space + current_char
                f.write(current_char)
            elif current_char == ',':
                current_char += '\n'
                j = 0
                while j < space_count - 1:
                    current_char += '    '
                    j += 1
                f.write(current_char + '   ')
            else:
                f.write(current_char)

思路:

读取当前字符

1. 首先判断是否在 ' " ' 中

  1.1. 在 ' " ' 中则判断当前这个字符是否是 ' " '

    1.1.1. 如果不是则直接写入

    1.1.2. 如果是 ' " ',则需要判断是否有转义字符 ' \ '

      1.1.2.1. 如果有则直接写入

      1.1.2.2. 如果没有则退出 ' " ' 状态

  1.2. 不在 ' " ' 中,判断当前字符类型

    1.2.1. 当前字符是 ' " ' ,则进入 ' " ' 状态

    1.2.2. 当前字符是 ' { '  ' } '  ' , ' 这三个则会进行相应的换行添加空格操作

posted on 2016-07-21 17:01  捞月丶  阅读(702)  评论(0编辑  收藏  举报

导航