How to beautify JSON in Python?

后端 未结 13 1362
渐次进展
渐次进展 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条回答
  • 2021-01-29 19:55

    It looks like jsbeautifier open sourced their tools and packaged them as Python and JS libs, and as CLI tools. It doesn't look like they call out to a web service, but I didn't check too closely. See the github repo with install instructions.


    From their docs for Python CLI and library usage:

    To beautify using python:

    $ pip install jsbeautifier
    $ js-beautify file.js
    

    Beautified output goes to stdout.

    To use jsbeautifier as a library is simple:

    import jsbeautifier
    res = jsbeautifier.beautify('your javascript string')
    res = jsbeautifier.beautify_file('some_file.js')
    

    ...or, to specify some options:

    opts = jsbeautifier.default_options()
    opts.indent_size = 2
    res = jsbeautifier.beautify('some javascript', opts)
    

    If you want to pass a string instead of a filename, and you are using bash, then you can use process substitution like so:

    $ js-beautify <(echo '{"some": "json"}')
    
    0 讨论(0)
提交回复
热议问题