zoukankan      html  css  js  c++  java
  • 批量格式化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

    效果: 

  • 相关阅读:
    androidlayout_weight的使用
    软件开发中的真理.
    apk,task,android:process与android:sharedUserId的区别
    WIFI连接
    go simple web server
    echo命令
    shell if
    linux grep命令(包括正则)
    make命令和Makefile文件
    linux中grep命令的用法
  • 原文地址:https://www.cnblogs.com/dzqdzq/p/11083171.html
Copyright © 2011-2022 走看看