json,dict資料寫入自動排版

來源:互聯網
上載者:User

標籤:

import jsonwith 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. 當前字元是 ‘ { ‘  ‘ } ‘  ‘ , ‘ 這三個則會進行相應的換行添加空格操作

json,dict資料寫入自動排版

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.