2014-09-03 17 views
16

in Python, Se ho un oggetto JSON obj, allora possouscita Coloring JSON in python

print json.dumps(obj, sort_keys=True, indent=4) 

al fine di ottenere una bella stampa dell'oggetto. È possibile migliorare ulteriormente l'output: aggiungere alcuni colori in particolare? Qualcosa come il risultato di [1]

cat foo.json | jq '.' 

[1] jq casella degli strumenti JSON dell'esercito svizzero: http://stedolan.github.io/jq/

+0

Qual è 'jq'? Che cosa fa? –

+0

Forse [ipython] (http://ipython.org/) ha qualcosa per questo, compra non so esattamente – stalk

+0

@Tichodroma: Aggiunto un riferimento – Dror

risposta

24

È possibile utilizzare Pygments per colorare l'output JSON. In base a quello che hai: esempio

formatted_json = json.dumps(obj, sort_keys=True, indent=4) 

from pygments import highlight, lexers, formatters 
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter()) 
print(colorful_json) 

uscita:

Output example of pygments colored code

+1

Cosa mi serve per evitare 'NameError: nome 'unicode' non è definito? – Dror

+5

Quindi stai usando python 3 e dovresti semplicemente usare 'colorful_json = highlight (formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter())' – arnuschky