0

I am constructing JSON dictionary with some special characters to print words in bold and various colors on the bash terminal like this:

# 'field' is a part of a bigger JSON document 'data'
field["value"] = '\033[1m' + string_to_print_in_bold + '\033[0m'

Later on, I'm calling dumps to create and print out my JSON:

print(json.dumps(data, indent=4, ensure_ascii=False))

However, on the terminal I see this:

"value": "\u001b[1mstring_to_print_in_bold\u001b[0m"

instead of

"value": "string_to_print_in_bold"

Note that ensure_ascii=False!

What am I missing?

Michael
  • 603
  • 2
  • 7
  • 8
  • 2
    What happens if you print(field[“value”]) – jkr Jun 03 '22 at 04:07
  • Which terminal you are using? – Rahul Jun 03 '22 at 04:11
  • Your expectations are off; JSON is a data serialization format, not something which should be interpreted when displayed. – tripleee Jun 03 '22 at 04:17
  • print(field[“value”]) works as expected – Michael Jun 03 '22 at 04:19
  • 1
    Normally adding `ensure_ascii` will [result the `\u` notation not be included](https://stackoverflow.com/questions/10865180/unicode-values-in-strings-are-escaped-when-dumping-to-json-in-python), the affected characters are not unicode but are control characters, and the [JSON specification requires them to be escaped](https://stackoverflow.com/questions/23112193/escaping-of-json-control-characters-within-string). So no, you can't do what you wanted to do, as your goal results in an invalid JSON document. – metatoaster Jun 03 '22 at 04:20
  • 1
    You are probably looking for [this solution](https://stackoverflow.com/questions/26459749/pretty-printing-json-with-ascii-color-in-python) involving a terminal formatter. Again, [the specification](https://stackoverflow.com/questions/47607810/control-characters-in-json-string) prohibits JSON from including those control characters unescaped. – metatoaster Jun 03 '22 at 04:27

1 Answers1

3

From a design perspective, you should separate formatting from your data. If you only want to pretty-print json with color, pygments provides a terminal text formatter to prettify your json output:

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

data = {"value": "myvalue"}
json_str = json.dumps(json_object, indent=4, sort_keys=True)
print(highlight(json_str, JsonLexer(), TerminalFormatter()))
monkut
  • 42,176
  • 24
  • 124
  • 155