Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty-printing JSON with ASCII color in python

I'm looking to print JSON to the command line, in python, with ASCII colors. For example, the (excellent) jq utility will color-ify JSON using bold ASCII colors like so:

  • input: curl --silent http://coinabul.com/api.php | jq .
  • output:
    jq output

Does anyone know how to accomplish this effect from Python? A couple of SO questions provide some good information on using ASCII colors from python (e.g. Print in terminal with colors using Python?), but this effect requires combining the pretty-printing machinery with the colorify-ing machinery in a different way, I think.

like image 448
Robert T. McGibbon Avatar asked Oct 20 '14 06:10

Robert T. McGibbon


People also ask

How do I print JSON beautify in Python?

Write Pretty Print JSON data to file To write a Python object as JSON formatted data into a file, json. dump() method is used. Like json. dumps() method, it has the indents and separator parameters to write beautified JSON.

How do I print JSON data in pretty format?

We can use the Python json module to pretty-print the JSON data. The json module is recommended to work with JSON files. We can use the dumps() method to get the pretty formatted JSON string.

What is JSON pretty print?

Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .

How do you print your response in JSON format?

print(response. json()) should give the the data formatted as JSON for this response.


1 Answers

Use Pygments library:

import json
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import TerminalFormatter

json_object = json.loads('{"foo":"bar"}')
json_str = json.dumps(json_object, indent=4, sort_keys=True)
print(highlight(json_str, JsonLexer(), TerminalFormatter()))
like image 55
kerma Avatar answered Sep 30 '22 19:09

kerma