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:
curl --silent http://coinabul.com/api.php | jq .
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.
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.
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.
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 .
print(response. json()) should give the the data formatted as JSON for this response.
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()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With