美文网首页
JSON大文件格式化

JSON大文件格式化

作者: 枫葉也 | 来源:发表于2019-01-27 12:20 被阅读0次

    问题

    工作中遇到了比较大的JSON文件(约10M),想要格式化显示,方便查看。使用IDEA自带的JSON格式化工具由于文件太大无法格式化。小一点的文件IDEA可以进行格式化,但是直接卡死无法操作。使用在线格式化JSON的网站进行格式化操作也会导致浏览器卡死。因此查找是否有相关的工具可以对JSON文本或文件进行格式化。

    目前找到的最好的方法是使用Python自带json工具包,使用简单的几句代码就可以进行格式化,大文本完全无压力,方便好用。主要有以下几种方法:

    1. 使用json.tool进行JSON格式化

    python -m json.tool input-file.json output-file.json
    # 指定使用Python3
    python3 -m json.tool input-file.json output-file.json
    

    input-file.json为输入文件,output-file.json为格式化后的文件。

    2. 使用mjson进行JSON格式化

    mjsonjson.tool使用方法相同,比较方便的地方在于可以直接使用,可以指定缩进大小。

    # 安装mjson
    pip install mjson
    # 指定缩进2空格
    mjson -i 2 input-file.json output-file.json
    

    3. 在VIM编辑器中进行JSON格式化

    vim中格式化是调用python json.tool格式化json文本。在命令行模式下输入:

    # VIM格式化的方法:
    :%!python -m json.tool
    
    # 使用 python3
    :%!python3 -m json.tool
    
    # 使用 mjson
    pip install mjson
    :%!mjson -i 2
    

    4. 解决中文乱码问题

    以上方法在使用中如果JSON文件有中文,则格式化后的文件中文会显示为乱码,可以这样解决。找到Pyhon安装环境下json.tool模块所在的位置,如Ubuntu自带Python环境下为/usr/lib/python3.5/json/tool.py,将该文件替换为以下内容。

    此处为Python3.5下该文件的替换,不同版本下拷贝出来该版本对应的json/tool.py,进行相应的修改使其支持中文再替换即可。

    r"""Command-line tool to validate and pretty-print JSON
    
    Usage::
    
        $ echo '{"json":"obj"}' | python -m json.tool
        {
            "json": "obj"
        }
        $ echo '{ 1.2:3.4}' | python -m json.tool
        Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
    
    """
    import argparse
    import collections
    import json
    import sys
    
    
    def main():
        prog = 'python -m json.tool'
        description = ('A simple command line interface for json module '
                       'to validate and pretty-print JSON objects.')
        parser = argparse.ArgumentParser(prog=prog, description=description)
        parser.add_argument('infile', nargs='?', type=argparse.FileType(),
                            help='a JSON file to be validated or pretty-printed')
        parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
                            help='write the output of infile to outfile')
        parser.add_argument('--sort-keys', action='store_true', default=False,
                            help='sort the output of dictionaries alphabetically by key')
        options = parser.parse_args()
    
        infile = options.infile or sys.stdin
        outfile = options.outfile or sys.stdout
        sort_keys = options.sort_keys
        with infile:
            try:
                if sort_keys:
                    obj = json.load(infile)
                else:
                    obj = json.load(infile,
                                    object_pairs_hook=collections.OrderedDict)
            except ValueError as e:
                raise SystemExit(e)
        with outfile:
            json.dump(obj, outfile, sort_keys=sort_keys, ensure_ascii=False, indent=2)
            outfile.write('\n')
    
    
    if __name__ == '__main__':
        main()
    

    5. 自定义工具进行格式化

    如果不想修改python自带的json.tool模块,可以自己编写py文件自己使用,解决中文乱码问题。

    • 使用以上解决中文乱码时贴出的代码,保存命名为json-tool.py,当前文件路径下调用python json-tool.py input-file.json output-file.json,即可正常使用。
    • 另一个格式化json文件工具 json-format.py
      使用:保存命名为json-format.py,当前文件路径下调用python json-format.py file.json,可以直接对file.json文件进行格式化输出。
    # encoding:utf-8
    import json
    import sys
    
    fp = open(sys.argv[1], 'r+')
    txt = fp.read()
    js = json.dumps(json.loads(txt), sort_keys=True, ensure_ascii=False, indent=2, separators=(',', ': '))
    fp.seek(0)
    fp.write(js)
    fp.close()
    

    相关文章

      网友评论

          本文标题:JSON大文件格式化

          本文链接:https://www.haomeiwen.com/subject/ruygjqtx.html