This blog discusses escaping quotes and backslashes in JSON.
I was doing a deep(er) dive into Microsoft’s Package Support Framework for MSIX recently, and wanted to have a play around with some of the “fixups” provided.
Whilst I was fiddling around trying to make things work (due to Microsoft’s inaccurate and/or poorly documented examples!), I stumbled upon shortcut arguments inside a config.json file and thought I’d write a short blog post to highlight escaping quotes and backslashes in JSON.
Escaping Quotes and Backslashes in JSON
When we escape a character in JSON, we essentially prefix the character with a backslash (\). So a "
would become \"
and a \
would become \\
.
The example we will use is to JSON encode the following string argument:
-logfile "%TEMP%\Alkane Path\alkane.log"
We notice that the log file path contains a space, so we need to surround the path in quotes.
Escaping Backslashes in JSON
The first step is to escape the backslashes by prefixing them with another backslash like so:
-logfile "%TEMP%\\Alkane Path\\alkane.log"
Escaping Quotes in JSON
The second step is to escape the quotes with a backslash like so:
-logfile \"%TEMP%\\Alkane Path\\alkane.log\"
JSON Encoded String
We then paste this value into our config.json file (excerpt):
{
"arguments": ""
}
Which results in a valid JSON file like so:
{
"arguments": "-logfile \"%TEMP%\\Alkane Path\\alkane.log\""
}
Most people probably won’t want (or need) to understand this level of detail since they’ll use the GUI of the MSIX Packaging Tool to apply fixups. But it’s useful to understand JSON for a plethora of other RESTful APIs, as well as our own free MSIX packaging tool.