標籤:
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資料寫入自動排版