How to beautify JSON in Python?

后端 未结 13 1489
渐次进展
渐次进展 2021-01-29 18:55

Can someone suggest how I can beautify JSON in Python or through the command line?

The only online based JSON beautifier which could do it was: http://jsonviewer.stack.h

13条回答
  •  萌比男神i
    2021-01-29 19:47

    A minimal in-python solution that colors json data supplied via the command line:

    import sys
    import json
    from pygments import highlight, lexers, formatters
    
    formatted_json = json.dumps(json.loads(sys.argv[1]), indent=4)
    colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter())
    print(colorful_json)
    

    Inspired by pjson mentioned above. This code needs pygments to be installed.

    Output example:

提交回复
热议问题