2014-05-18 4 views
29

Ich weiß, dass die Python-Standardbibliothek pprint zum Drucken von Python-Datentypen geeignet ist. Ich werde jedoch immer JSON-Daten abrufen, und ich frage mich, ob es eine einfache und schnelle Möglichkeit gibt, JSON-Daten schön zu drucken.pretty-print json in python (pythonischer weg)

No pretty-Druck:

import requests 
r = requests.get('http://server.com/api/2/....') 
r.json() 

Mit ziemlich Druck:

>>> import requests 
>>> from pprint import pprint 
>>> r = requests.get('http://server.com/api/2/....') 
>>> pprint(r.json()) 
+0

Warum Sie nicht verwenden ' Drucken? – thefourtheye

+0

In Ihrem Beispiel drucken Sie JSON nirgendwo. Sie dekodieren es (indem Sie 'r.json()'), also ist es nur eine Python-Datenstruktur danach. Also, was genau willst du schön drucken? Python-Datenstrukturen oder JSON? –

+0

mmm du hast Recht. Beide Fälle. – autorun

Antwort

57

Pythons builtin JSON module kann damit umgehen für Sie:

>>> import json 
>>> a = {'hello': 'world', 'a': [1, 2, 3, 4], 'foo': 'bar'} 
>>> print(json.dumps(a, indent=2)) 
{ 
    "hello": "world", 
    "a": [ 
    1, 
    2, 
    3, 
    4 
    ], 
    "foo": "bar" 
} 
Verwandte Themen