How to prettyprint a JSON file?

前端 未结 13 825
滥情空心
滥情空心 2020-11-22 01:53

I have a JSON file that is a mess that I want to prettyprint. What\'s the easiest way to do this in Python?

I know PrettyPrint takes an \"object\", which I think can

相关标签:
13条回答
  • 2020-11-22 02:17

    Pygmentize + Python json.tool = Pretty Print with Syntax Highlighting

    Pygmentize is a killer tool. See this.

    I combine python json.tool with pygmentize

    echo '{"foo": "bar"}' | python -m json.tool | pygmentize -l json
    

    See the link above for pygmentize installation instruction.

    A demo of this is in the image below:

    0 讨论(0)
  • 2020-11-22 02:18

    To be able to pretty print from the command line and be able to have control over the indentation etc. you can set up an alias similar to this:

    alias jsonpp="python -c 'import sys, json; print json.dumps(json.load(sys.stdin), sort_keys=True, indent=2)'"
    

    And then use the alias in one of these ways:

    cat myfile.json | jsonpp
    jsonpp < myfile.json
    
    0 讨论(0)
  • 2020-11-22 02:19
    def saveJson(date,fileToSave):
        with open(fileToSave, 'w+') as fileToSave:
            json.dump(date, fileToSave, ensure_ascii=True, indent=4, sort_keys=True)
    

    It works to display or save it to a file.

    0 讨论(0)
  • 2020-11-22 02:20

    I had a similar requirement to dump the contents of json file for logging, something quick and easy:

    print(json.dumps(json.load(open(os.path.join('<myPath>', '<myjson>'), "r")), indent = 4 ))
    

    if you use it often then put it in a function:

    def pp_json_file(path, file):
        print(json.dumps(json.load(open(os.path.join(path, file), "r")), indent = 4))
    
    0 讨论(0)
  • 2020-11-22 02:25

    You could use the built-in module pprint (https://docs.python.org/3.6/library/pprint.html).

    How you can read the file with json data and print it out.

    import json
    import pprint
    
    json_data = None
    with open('file_name.txt', 'r') as f:
        data = f.read()
        json_data = json.loads(data)
    
    pprint.pprint(json_data)
    
    0 讨论(0)
  • 2020-11-22 02:26

    Here's a simple example of pretty printing JSON to the console in a nice way in Python, without requiring the JSON to be on your computer as a local file:

    import pprint
    import json 
    from urllib.request import urlopen # (Only used to get this example)
    
    # Getting a JSON example for this example 
    r = urlopen("https://mdn.github.io/fetch-examples/fetch-json/products.json")
    text = r.read() 
    
    # To print it
    pprint.pprint(json.loads(text))
    
    0 讨论(0)
提交回复
热议问题