10

I have the following data stucture:

{'row_errors': {'hello.com': {'template': [u'This field is required.']}}}

When I use pprint in Python, I am getting

{'row_errors': {'hello.com': {'template': [u'This field is required.']}}}

However, I would very much like it to be printed like:

{'row_errors': 
    {'hello.com': 
        {'template': [u'This field is required.']}}}

Is this possible to configure via pprint?
I prefer pprint because I am printing this inside a Jinja template.

informatik01
  • 16,038
  • 10
  • 74
  • 104
Tinker
  • 4,165
  • 6
  • 33
  • 72
  • 3
    I propose you the alternative: `import json; print(json.dumps(d, indent=4))` – wim Jun 29 '17 at 18:50
  • 2
    `pprint()` isn't all that configurable. – Martijn Pieters Jun 29 '17 at 18:51
  • Try to change the width argument to 40: `pprint(..., width=40)`. The result however is not 100% match like the one you need. – GIZ Jun 29 '17 at 20:12
  • If you're just looking to visualize the nesting structure (and don't want extra lines for brackets), consider https://pypi.org/project/asciitree/. Nice visual, once you get OrderedDict structure right. (Not affiliated, just a fan). – combinatorist Feb 08 '22 at 09:36

1 Answers1

4

Like the wim suggested in the comments, you can use json.dumps().

Quoting from Blender's answer:

The json module already implements some basic pretty printing with > the indent parameter:

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print json.dumps(parsed, indent=4, sort_keys=True)
[
    "foo", 
    {
        "bar": [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]
informatik01
  • 16,038
  • 10
  • 74
  • 104
mdegis
  • 2,078
  • 2
  • 21
  • 39
  • This adds a line for each json open / close bracket, so much longer format than OP. (Consider my asciitree comment directly on OP.) – combinatorist Feb 08 '22 at 09:38