Dan's solution is just wrong, and Ismail's in incomplete.
__str__()is not called,__repr__()is called.__repr__()should return a string, as pformat does.- print normally indents only 1 character and tries to save lines. If you are trying to figure out structure, set the width low and indent high.
Here is an example
class S:
def __repr__(self):
from pprint import pformat
return pformat(vars(self), indent=4, width=1)
a = S()
a.b = 'bee'
a.c = {'cats': ['blacky', 'tiger'], 'dogs': ['rex', 'king'] }
a.d = S()
a.d.more_c = a.c
print(a)
This prints
{ 'b': 'bee',
'c': { 'cats': [ 'blacky',
'tiger'],
'dogs': [ 'rex',
'king']},
'd': { 'more_c': { 'cats': [ 'blacky',
'tiger'],
'dogs': [ 'rex',
'king']}}}
Which is not perfect, but passable.
Answer from Charles Merriam on Stack OverflowDan's solution is just wrong, and Ismail's in incomplete.
__str__()is not called,__repr__()is called.__repr__()should return a string, as pformat does.- print normally indents only 1 character and tries to save lines. If you are trying to figure out structure, set the width low and indent high.
Here is an example
class S:
def __repr__(self):
from pprint import pformat
return pformat(vars(self), indent=4, width=1)
a = S()
a.b = 'bee'
a.c = {'cats': ['blacky', 'tiger'], 'dogs': ['rex', 'king'] }
a.d = S()
a.d.more_c = a.c
print(a)
This prints
{ 'b': 'bee',
'c': { 'cats': [ 'blacky',
'tiger'],
'dogs': [ 'rex',
'king']},
'd': { 'more_c': { 'cats': [ 'blacky',
'tiger'],
'dogs': [ 'rex',
'king']}}}
Which is not perfect, but passable.
pprint.pprint doesn't return a string; it actually does the printing (by default to stdout, but you can specify an output stream). So when you write print record, record.__str__() gets called, which calls pprint, which returns None. str(None) is 'None', and that gets printed, which is why you see None.
You should use pprint.pformat instead. (Alternatively, you can pass a StringIO instance to pprint.)
Pretty print JSON from URL
python - How to prettyprint a JSON file? - Stack Overflow
python - Is there a built-in function to print all the current properties and values of an object? - Stack Overflow
New Protocol for Pretty Printing
Videos
Hello Everyone,
I've hit a frustrating wall and after much googling I took a deep breath and felt the best approach was to ask you all for advice.
I'm making a very simple script and need assistance with what tool I should use to move forward.
Step 1: Fetch the URL Step 2: Make the JSON pretty. Such as a top-down listing of Title and URL only.
import requests
#make the URL call
page = requests.get('http://gleamlist.com:5000/api')
#verify the page has content - just for testing.
print(page.content)I've tried using the json module but confuse myself and I've thought maybe BS4 would help but also confuse myself. I believe JSON is basically a dictionary and I want to parse out the info. Could anyone assist me with some tips or a specific topic to research and implement please?
Use the indent= parameter of json.dump() or json.dumps() to specify how many spaces to indent by:
>>> import json
>>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4))
[
"foo",
{
"bar": [
"baz",
null,
1.0,
2
]
}
]
To parse a file, use json.load():
with open('filename.txt', 'r') as handle:
parsed = json.load(handle)
You can do this on the command line:
python3 -m json.tool some.json
(as already mentioned in the commentaries to the question, thanks to @Kai Petzke for the python3 suggestion).
Actually python is not my favourite tool as far as json processing on the command line is concerned. For simple pretty printing is ok, but if you want to manipulate the json it can become overcomplicated. You'd soon need to write a separate script-file, you could end up with maps whose keys are u"some-key" (python unicode), which makes selecting fields more difficult and doesn't really go in the direction of pretty-printing.
You can also use jq:
jq . some.json
and you get colors as a bonus (and way easier extendability).
Addendum: There is some confusion in the comments about using jq to process large JSON files on the one hand, and having a very large jq program on the other. For pretty-printing a file consisting of a single large JSON entity, the practical limitation is RAM. For pretty-printing a 2GB file consisting of a single array of real-world data, the "maximum resident set size" required for pretty-printing was 5GB (whether using jq 1.5 or 1.6). Note also that jq can be used from within python after pip install jq.
You want vars() mixed with pprint():
from pprint import pprint
pprint(vars(your_object))
You are really mixing together two different things.
Use dir(), vars() or the inspect module to get what you are interested in (I use __builtins__ as an example; you can use any object instead).
>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__
Print that dictionary however fancy you like:
>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...
or
>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'DeprecationWarning',
...
>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
'AssertionError': <type 'exceptions.AssertionError'>,
'AttributeError': <type 'exceptions.AttributeError'>,
...
'_': [ 'ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'DeprecationWarning',
...
Pretty printing is also available in the interactive debugger as a command:
(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
'AssertionError': <type 'exceptions.AssertionError'>,
'AttributeError': <type 'exceptions.AttributeError'>,
'BaseException': <type 'exceptions.BaseException'>,
'BufferError': <type 'exceptions.BufferError'>,
...
'zip': <built-in function zip>},
'__file__': 'pass.py',
'__name__': '__main__'}
I've recently documented a protocol in Rich to add pretty printing to arbitrary objects.
The problem was that containers like dicts, lists, sets etc could be formatted over multiple lines, but custom classes are limited to a string that can be generated from __repr__. The new protocol in Rich adds a __rich_repr__ method which allows an object to declare how it should be pretty printed.
Looking for feedback. Here are the docs.
Here's an example of a __rich_repr__ method.
And here's what it looks like when you pretty print a Bird instance:
I'm trying to use the pokebase wrapper just to explore and I'm really struggling with it.
I just want to print all the moves a pokemon has but they show up as locations in memory instead of the actual values. I'm not sure how to get the data out of this.
import pokebase as pb pokemon = pb.pokemon(1) print(pokemon.moves)
Example of results:
[<pokebase.interface.APIMetadata object at 0x000001E774593C70>, <pokebase.interface.APIMetadata object at 0x000001E774543940>, <pokebase.interface.APIMetadata object at 0x000001E774593B20>]