im2wddrf
im2wddrf

Reputation: 581

Python: Read in Colors Codes from JSON

I am interested in creating a project where a python script will create colored output. The structure of my project is such that I would like to create a settings.json file (handled by users) that contains color codes (ANSI).

Here is what my settings.json file looks like. Note that in a bash profile, you'd normally use one escape character to indicate color codes but Python will not allow me to read a file with only one escape character. :

{
  "column_head_color": {
    "group1": "\\033[91m",
    "group2": null
  }
}

And here is the main module:

import json


# import settings
with open('settings.json', encoding='utf-8') as file:
    settings = json.load(file)


for column in settings['column_head_color']:
    color_setting = settings['column_head_color'][column]

    if color_setting is None:
    # if setting is null, reset color
        settings['column_head_color'][column] = "\033[0m"   # reset; if I change the string to "\\033[94m", output shows actual color

    else:
        # if there is a color code present, should I replace "\\" with "\"?
        settings['column_head_color'][column] = settings['column_head_color'][column].replace("\\\\", "\\")



print("{}This is the group1".format(settings['column_head_color']['group1']))       # output shows the color code, but it does not actually format the text
print("{}This is the group2".format(settings['column_head_color']['group2']))       # output here works, because it was hard coded manually

I have tried replacing two escape characters with one, and I have tried using the repr() function, but to no avail. I have only gone as far as showing an output that looks like something like this:

>>> python main.py
\033[91mOutput

For group2, the color code works because I manually entered the code in the script. But when I read it in a similar string for group1 from the JSON file, Python does not interpret it the same way. How do I prompt my python program to interpret that string as a color code?

Upvotes: 0

Views: 1060

Answers (1)

anomynous
anomynous

Reputation: 36

You could follow these steps to make it work:

  1. Format your json file like this:

    {
        "Black" : "30",
        "Red" : "31",
        "Green" : "32",
        "Yellow" : "33",
        "Blue" : "34",
        "Magenta" : "35",
        "Cyan" : "36",
        "White" : "37"
    }
    
  2. Find and load the JSON file

    // Replace PATH_TO__FILE and FILE_NAME accordingly  
    const colors = require('PATH_TO_FILE/FILE_NAME.json')
    
  3. Create a function to output in different colors. For instance:

    function consoleLogColor(color, text) {
        console.log(`\x1b[${colors[color]}m%s\x1b[0m`, text);
    }
    consoleLogColor('Blue', 'HI');
    

Upvotes: 2

Related Questions