7

I have the following datastucture:

{'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).

Tinker
  • 3,471
  • 6
  • 29
  • 61
  • 2
    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. – direprobs 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

1

Like the wim suggested on comments, you can use json.dump.

Quoting from Blender's answer, you can achieve this like this:

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
        ]
    }
]
mdegis
  • 1,988
  • 2
  • 21
  • 34
  • 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