简体   繁体   English

Python - 将特殊字符插入 JSON 字符串以在 bash 终端上打印它们

[英]Python - Inserting special characters into JSON string to print them on bash terminal

["

I am constructing JSON dictionary with some special characters to print words in bold and various colors on the bash terminal like this:<\/i>我正在构建带有一些特殊字符的 JSON 字典,以便在 bash 终端上以粗体和各种颜色打印单词,如下所示:<\/b><\/p>

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

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:如果您只想漂亮地打印带有颜色的 json, pygments提供了一个终端文本格式化程序来美化您的 json 输出:

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()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM