批量格式化json

单个文件格式化工具: vscode和sublime都有格式化json的插件。 

但是笔者遇到的情况是有几百个文件需要格式化,不可能每个文件都打开,进行分别格式化。

于是写了一个python脚本,非常强大,支持中文。批量格式化代码如下:

# coding:utf8
import json
import sys,os

def getFileCon(filename):
  if not os.path.isfile(filename):
    return

  with open(filename, "r") as f:
    con = f.read()
    f.close()
    return con

def writeFile(filepath,con):
  with open(filepath, "w") as f:
    f.write(con)
    f.close()

if __name__ == "__main__":
  fl = os.listdir(".")
  for f in fl:
    g = f
    if not f.endswith(".json"):
      continue
    try:
      con = json.loads(getFileCon(f))
      # print con
      # writeFile(f,json.dumps(con,indent=4,ensure_ascii=False).decode('utf8'))
      writeFile(f,json.dumps(con,indent=4,ensure_ascii=False))
      print (g,'OK')
    except Exception as e:
      print (g,'is not json format')

将这个脚本拷贝到需要格式化的目录,然后执行 python format.py

效果: 

原文地址:https://www.cnblogs.com/dzqdzq/p/11083171.html