👋 Hello! I'm Alphonsio the robot. Ask me a question, I'll try to answer.

pprint json in python

There are several ways to display a JSON string in Python:


With JSON : the first option is to use the json library:

# Import json library
import json
# JSON to display
str_json = '{"key1":"val1", "key2":"val2"}'
# parse the string (str -> dict)
parsed = json.loads(str_json)
# Display the indented JSON
print(json.dumps(parsed, indent=4))

The above code displays:

{
    "key1": "val1",
    "key2": "val2"
}



Pretty print : the second option is to use the pprint library:

# Import json
import json
# Import pprint
from pprint import pprint
# JSON to display
str_json = '{"key1":"val1", "key2":"val2"}'
# Parse the JSONstring (str -> dict)
parsed = json.loads(str_json)
# Display the JSON with pretty print
pprint(parsed, width=1)

The above code displays:

{'key1': 'val1',
 'key2': 'val2'}

More