Python how to pretty print data - JSON, XML, dict

In this post:

Python pretty print JSON indent 4

For JSON you can use method dumps of module JSON. You have several options like:

  • indent - the number of the indentation symbols
  • sort_keys - to sort keys or not
import json

players_json = '[{"players":["Ronaldo", 7, "Kaka", 15], "bench":["Robinho", 11]}, "team"]'
res = json.loads(players_json)
print (json.dumps(res, indent=4, sort_keys=True))

result:

[
    {
        "bench": [
            "Robinho",
            11
        ],
        "players": [
            "Ronaldo",
            7,
            "Kaka",
            15
        ]
    },
    "team"
]

Python pretty print JSON indent 2

You can indent on 2 without sorting by keys and keeping the old order of the records by:

import json
team_json = {'team': 'Brazil', 'players': [7, 8, 11], 'best': 'Pele'}
print(json.dumps(team_json, indent=2, sort_keys=False))

result:

{
  "players": [
    7,
    8,
    11
  ],
  "team": "Brazil",
  "best": "Pele"
}

note: if you don't specify - sort_keys=False -then the result will be sorted by default.

Python pretty print dict with pprint

For dictionaries/dict in Python you can use also pprint to output them in better format with records on new lines:

import pprint
a = {'Pele': 1758, 'Maradona': 1654, 'Messi': {1:1424, 2:1321}, 'Ronaldo': {1:1248, 2:1369}}
pprint.pprint(a, width=1)

result:

{'Maradona': 1654,
 'Messi': {1: 1424,
           2: 1321},
 'Pele': 1758,
 'Ronaldo': {1: 1248,
             2: 1369}}

Python pretty print XML/HTML with pprint

For XML and HTML you can pretty print by using pprint module. You can find simple example for XML:

from lxml import etree, html

xml_doc = html.fromstring("<Team><Brazil><Players><Player>Pele</Player><Player>Kaka</Player></Players></Brazil></Team>")
print(etree.tostring(xml_doc, encoding='unicode', pretty_print=True))

result:

<team>
  <brazil>
    <players>
      <player>Pele</player>
      <player>Kaka</player>
    </players>
  </brazil>
</team>

Python pretty print JSON from URL address by pprint

Very often you will get result from URL in form of JSON. If you want to get the result in good format with indentations and each record of new line you can do it by using pprint. In this example we are getting the information for Google Maps for London. You can find the result with and without format:

import requests
import pprint

url_address = "https://maps.googleapis.com/maps/api/geocode/json"
resp = requests.get(url_address, params = {'address': 'London'})

print(resp.json())
pprint.pprint(resp.json(), width=1)

result:

No pretty print:

{'results': [{'types': ['locality', 'political'], 'formatted_address': 'New York, NY, USA', 'geometry': {'location': {'lat': 40.7127753, 'lng': -74.0059728}, 'bounds': {'northeast': {'lat': 40.9175771, 'lng': -73.70027209999999}, 'southwest': {'lat': 40.4773991, 'lng': -74.25908989999999}}, 'viewport': {'northeast': {'lat': 40.9175771, 'lng': -73.70027209999999}, 'southwest': {'lat': 40.4773991, 'lng': -74.25908989999999}}, 'location_type': 'APPROXIMATE'}, 'place_id': 'ChIJOwg_06VPwokRYv534QaPC8g', 'address_components': [{'short_name': 'New York', 'types': ['locality', 'political'], 'long_name': 'New York'}, {'short_name': 'NY', 'types': ['administrative_area_level_1', 'political'], 'long_name': 'New York'}, {'short_name': 'US', 'types': ['country', 'political'], 'long_name': 'United States'}]}], 'status': 'OK'}

Pretty print:

{'results': [{'address_components': [{'long_name': 'New '
                                                   'York',
                                      'short_name': 'New '
                                                    'York',
                                      'types': ['locality',
                                                'political']},
                                     {'long_name': 'New '
                                                   'York',
                                      'short_name': 'NY',
                                      'types': ['administrative_area_level_1',
                                                'political']},
                                     {'long_name': 'United '
                                                   'States',
                                      'short_name': 'US',
                                      'types': ['country',
                                                'political']}],
              'formatted_address': 'New '
                                   'York, '
                                   'NY, '
                                   'USA',
              'geometry': {'bounds': {'northeast': {'lat': 40.9175771,
                                                    'lng': -73.70027209999999},
                                      'southwest': {'lat': 40.4773991,
                                                    'lng': -74.25908989999999}},
                           'location': {'lat': 40.7127753,
                                        'lng': -74.0059728},
                           'location_type': 'APPROXIMATE',
                           'viewport': {'northeast': {'lat': 40.9175771,
                                                      'lng': -73.70027209999999},
                                        'southwest': {'lat': 40.4773991,
                                                      'lng': -74.25908989999999}}},
              'place_id': 'ChIJOwg_06VPwokRYv534QaPC8g',
              'types': ['locality',
                        'political']}],
 'status': 'OK'}

References

Related Article