How to beautify JSON in Python?

后端 未结 13 1349
渐次进展
渐次进展 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:46

    Your data is poorly formed. The value fields in particular have numerous spaces and new lines. Automated formatters won't work on this, as they will not modify the actual data. As you generate the data for output, filter it as needed to avoid the spaces.

    0 讨论(0)
  • 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:

    0 讨论(0)
  • 2021-01-29 19:48

    With jsonlint (like xmllint):

    aptitude install python-demjson
    jsonlint -f foo.json
    
    0 讨论(0)
  • 2021-01-29 19:50

    You could pipe the output to jq. If you python script contains something like

    print json.dumps(data)
    

    then you can fire:

    python foo.py | jq '.'
    
    0 讨论(0)
  • 2021-01-29 19:53

    From the command-line:

    echo '{"one":1,"two":2}' | python -mjson.tool
    

    which outputs:

    {
        "one": 1, 
        "two": 2
    }
    

    Programmtically, the Python manual describes pretty-printing JSON:

    >>> import json
    >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
    {
        "4": 5,
        "6": 7
    }
    
    0 讨论(0)
  • 2021-01-29 19:53

    The cli command I've used with python for this is:

    cat myfile.json | python -mjson.tool
    

    You should be able to find more info here:

    http://docs.python.org/library/json.html

    0 讨论(0)
提交回复
热议问题