Search code examples
jsoncolorsansi-escape

How do I add ANSI color encodings into JSON?


I'm trying to create a json file that will hold all the tags for some system logging, like for example:

console.log(`${logs["SYSTEM"].SHUTDOWN} - The bot has been shut down.`)

However, it doesn't allow me to create ANSI color escape characters for some reason. This is how my logs.json looks:

{
    "SYSTEM": {
        "SUCCESS": "[\x1B[48;2;0;0;0mSYSTEM\x1B[0m]::[\x1B[38;2;0;255;0m\x1B[48;2;0;0;0mSUCCESS\x1B[0m]",
        "RELOADED": "[\x1B[48;2;0;0;0mSYSTEM\x1B[0m]::[\x1B[38;2;0;255;0m\x1B[48;2;0;0;0mRELOADED\x1B[0m]",
        "RELOADING": "[\x1B[48;2;0;0;0mSYSTEM\x1B[0m]::[\x1B[38;2;255;158;3m\x1B[48;2;0;0;0mRELOADING...\x1B[0m]",
        "ERROR": "[\x1B[48;2;0;0;0mSYSTEM\x1B[0m]::[\x1B[38;2;255;0;0m\x1B[48;2;0;0;0mERROR\x1B[0m]",
        "SHUTDOWN": "[\x1B[48;2;0;0;0mSYSTEM\x1B[0m]::[\x1B[38;2;255;0;0m\x1B[48;2;0;0;0mSHUTDOWN\x1B[0m]"
    }

}

vs code tells me the error is an "Invalid escape character in string", but I'm not sure how I'm supposed to fix this.


Solution

  • Since the \ is an escape character, I think you just need to double its presence in all the strings.

    {
        "SYSTEM": {
            "SUCCESS": "[\\x1B[48;2;0;0;0mSYSTEM\\x1B[0m]::[\\x1B[38;2;0;255;0m\\x1B[48;2;0;0;0mSUCCESS\\x1B[0m]",
            "RELOADED": "[\\x1B[48;2;0;0;0mSYSTEM\\x1B[0m]::[\\x1B[38;2;0;255;0m\\x1B[48;2;0;0;0mRELOADED\\x1B[0m]",
            "RELOADING": "[\\x1B[48;2;0;0;0mSYSTEM\\x1B[0m]::[\\x1B[38;2;255;158;3m\\x1B[48;2;0;0;0mRELOADING...\\x1B[0m]",
            "ERROR": "[\\x1B[48;2;0;0;0mSYSTEM\\x1B[0m]::[\\x1B[38;2;255;0;0m\\x1B[48;2;0;0;0mERROR\\x1B[0m]",
            "SHUTDOWN": "[\\x1B[48;2;0;0;0mSYSTEM\\x1B[0m]::[\\x1B[38;2;255;0;0m\\x1B[48;2;0;0;0mSHUTDOWN\\x1B[0m]"
        }
    }