How to 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'}
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'}
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'}
# | ID | Query | URL | Count |
---|