單個文件格式化工具: vscode和sublime都有格式化json的插件。
但是筆者遇到的情況是有幾百個文件需要格式化,不可能每個文件都打開,進行分別格式化。
於是寫了一個python腳本,非常強大,支持中文。批量格式化代碼如下:
#coding:utf8 import json import sys,os reload(sys) sys.setdefaultencoding('utf-8') def getFileCon(filename): if not os.path.isfile(filename): return try: f = open(filename, "r") con = f.read() f.close() return con except Exception as e: pass # 向文件寫內容 def writeFile(filepath,con): if con: f = file(filepath, "w") f.write(con) f.close() else: print (filepath, "filepath FAIL") if __name__ == "__main__": fl = os.listdir(".") for f in fl: g = f try: con = json.loads(getFileCon(f)) # print con writeFile(f,json.dumps(con,indent=4,ensure_ascii=False).decode('utf8')) print (g,'OK') except Exception as e: print (g,e)
將這個腳本拷貝到需要格式化的目錄,然后執行 python format.py
效果: