批量格式化json

批量格式化json,第1张

批量格式化json

单个文件格式化工具: 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

效果:

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/586971.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存