Question #173   Submitted by Answiki on 10/05/2020 at 06:40:39 PM UTC

How to pprint JSON in Python?

Answer   Submitted by Answiki on 09/21/2022 at 11:09:42 AM UTC

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'}

5 events in history
Answer by Answiki on 09/21/2022 at 11:09:42 AM

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'}

Question by Answiki 09/21/2022 at 11:06:19 AM
How to display a JSON string in Python with indentation?
Question by Answiki 10/05/2020 at 06:40:39 PM
How to pprint JSON in Python?
Answer by Answiki on 10/05/2020 at 06:40:29 PM

The following code shows an example of JSON pretty print in Python:

>>> import json
>>> from pprint import pprint
>>> str_json = '{"key1":"val1", "key2":"val2"}'
>>> parsed = json.loads(str_json)
>>> pprint(parsed, width=1)
{'key1': 'val1',
 'key2': 'val2'}

Question by Answiki 10/05/2020 at 06:39:17 PM
How to pretty print JSON in Python?
# ID Query URL Count

Icons proudly provided by Friconix.