I have some code with quotation marks that I want to use as a snippet. Unfortunately, JSON requires me to use them in "body" array in my settings. I tried to use different types of quotation marks, but Visual Studio highlights it in red:
enter image description here
What can I do to include quotation marks in my snippet?
7 Answers 7
Use \ to escape the double quotes.
A sample snippet looks like this:
"My quoted snippet": {
"prefix": "quot",
"body": [
"Hello \"User\""
],
"description": "Print snippets with quotes"
}
When you execute this snippet it will print: Hello "User"
3 Comments
Invalid characters in string. Control characters must be escaped"echo \"<pre>\";",Use can simply use \ (backward slash) if you want to use double quotes or any other thing in json
Example :
"print statement":{
"prefix": "print",
"body": "print(\"1ドル\")",
"description": "print anything in python"
}
Comments
I was hoping there was a online converter available for this purpose to convert the code to correctly encoded code, but seems noone did that as of yet...
Remember that json also needs escaping with \ so you might have to \ for it to work correctly, an example from #42669459 has this sollution:
What to encode: ${code}
Sollution:
"Return Code With Squirly And Dollar": {
"prefix": "code_snippet",
"body" : [
"\\${code\\}"
],
"description": "Code Snippet"
}
Comments
My environment is Visual Studio 2022.
I wanted to create a snippet that produces the following line of code:
_logger.LogInformation($"")
The following worked for me
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>logger information</Title>
<Shortcut>loginfo</Shortcut>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[_logger.LogInformation($$" ");]]>
</Code>
<Imports>
<Import>
</Import>
</Imports>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Comments
I don't know if you used tabs in your real snippet, but if yes, this answer fixed my issue.
You can replace tabs characters by spaces, or maybe use \t instead.
Comments
Maybe this will help someone, I found that I getting an "invalid escape character" message but the problem was with a path rather than the double quotes themselves. Here's what I ended up doing and it works fine.
"body": "<cfdump var=\"#arguments#\" output=\"C:\\webmx\\www\\myDump.html\" format=\"html\">",
Comments
Using @Wosi 's answer to create a snippet that creates a snippet template.
We covert this:
"snip": {
"prefix": "snip",
"body": [
""
],
"description": "Template to create a new snippet"
},
INTO:
"snip": {
"prefix": "snip",
"body": [
"\"1ドル\": { "
" \"prefix\": \"1ドル\", "
" \"body\": [ "
" \"2ドル\" "
" ], "
" \"description\": \"3ドル\" "
"}, "
],
"description": "Template to create a new snippet"
},