当单个甚至单行Json文件大小超过100M时,无论是哪个文本编辑器在处理时都会显得吃力,接下来介绍一种非常方便的方式,快速格式化大型Json文件。

:::info Python 自带json-tool 在转换是会导致中文乱码,以下在原有基础上进行了优化,并增加中文支持 :::

No BB, Show Code

  1. """
  2. Command-line tool to validate and pretty-print JSON
  3. Usage::
  4. $ python3 json-tool.json import.json output.json
  5. Need Python 3.
  6. """
  7. import argparse
  8. import collections
  9. import json
  10. import sys
  11. def main():
  12. prog = 'python -m json.tool'
  13. description = ('A simple command line interface for json module '
  14. 'to validate and pretty-print JSON objects.')
  15. parser = argparse.ArgumentParser(prog=prog, description=description)
  16. parser.add_argument('infile', nargs='?', type=argparse.FileType(),
  17. help='a JSON file to be validated or pretty-printed')
  18. parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
  19. help='write the output of infile to outfile')
  20. parser.add_argument('--sort-keys', action='store_true', default=False,
  21. help='sort the output of dictionaries alphabetically by key')
  22. options = parser.parse_args()
  23. infile = options.infile or sys.stdin
  24. outfile = options.outfile or sys.stdout
  25. sort_keys = options.sort_keys
  26. with infile:
  27. try:
  28. if sort_keys:
  29. obj = json.load(infile)
  30. else:
  31. obj = json.load(infile,
  32. object_pairs_hook=collections.OrderedDict)
  33. except ValueError as e:
  34. raise SystemExit(e)
  35. with outfile:
  36. json.dump(obj, outfile, sort_keys=sort_keys, ensure_ascii=False, indent=2)
  37. outfile.write('\n')
  38. if __name__ == '__main__':
  39. main()

RUNNING

将以上代码文件保存为 json-tool.json,然后使用 Python3 运行即可

  1. python3 json-tool.json 190720_190730.json 06.json