Contents

pretty print json using rich

0

Here are a few examples of pretty printing json from a command line terminal. As you can see in the example output, rich console can output json with proper indention and color syntax highlighting.

Pretty Print JSON string

from rich.console import Console

console = Console()

json = """{"User": { "name": "John Doe", "email": "[email protected]", "age": 32,
"gender": "Male", "isActive": true, "isAdmin":false}}"""

console.print_json(json)

Output

/code/rich/pretty-print-json-using-rich/prettyprint-json-rich.png
PrettyPrint JSON

Pretty Print API response

import urllib
from rich.console import Console

console = Console()

url = "https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=5&gsrsearch=%27Python%27"
resp = urllib.get(url)

console.print_json(resp)

Output

https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=5&gsrsearch=%27Python%27
{
    "batchcomplete": "",
    "continue": {
        "gsroffset": 5,
        "continue": "gsroffset||"
    },
    "query": {
        "pages": {
            "271890": {
                "pageid": 271890,
                "ns": 0,
                "title": "Ball python",
                "index": 4
            },
            "21356332": {
                "pageid": 21356332,
                "ns": 0,
                "title": "History of Python",
                "index": 5
            },
            "18942": {
                "pageid": 18942,
                "ns": 0,
                "title": "Monty Python",
                "index": 3
            },
            "46332325": {
                "pageid": 46332325,
                "ns": 0,
                "title": "Python",
                "index": 2
            },
            "23862": {
                "pageid": 23862,
                "ns": 0,
                "title": "Python (programming language)",
                "index": 1
            }
        }
    }
}
/code/rich/pretty-print-json-using-rich/prettyprint-json-from-wikipedia-api.png
PrettyPrint JSON response from API

About Rich

rich - Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal