How to escape double quotes in JSON
Asked Answered
P

8

534

I'm trying to show double quotes but it shows one of the backslashes:

"maingame": {
    "day1": {
        "text1": "Tag 1",
        "text2": "Heute startet unsere Rundreise \\\"Example text\\\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.</strong> "
    }
}

When rendering in the html it shows as \"Example text\". What is the correct way?

Pathe answered 26/3, 2013 at 12:46 Comment(0)
M
740

Try this:

"maingame": {
  "day1": {
    "text1": "Tag 1",
     "text2": "Heute startet unsere Rundreise \" Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.</strong> "
  }
}

(just one backslash (\) in front of quotes).

Mayer answered 26/3, 2013 at 12:49 Comment(10)
@DWGuru this has nothing to do with comments, it's an escape sequence as described at ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf (Par. 9 - Strings) where it says: All characters may be placed within the quotation marks except for the characters that must be escaped and then it specifies: \" represents the quotation mark character (U+0022)Kalmar
For some reason, this doesn't work with JSON.parse() in JS.Ansell
@Ansell var r = '{"a":"quotes\"here"}' // "{"a":"quotes"here"}". What you need is to escape the backslash in the string too, hence use tripple backslash, ie. var r = '{"a":"quotes\\\"here"}' // "{"a":"quotes\"here"}". After that you can use JSON.parse(r)Rubberneck
@Rubberneck It seems that all you need is double backslash. '{"a":"quotes\\"here"}'Ansell
@Ansell Yes, that's true, because inside single quotes ' ', double quotes can be used without escaping. I kinda mixed two things together, I realised that after posting. Inside " it is still necessary to use tripple escapes though " \\\" " vs ' \\" '.Rubberneck
@Rubberneck although there are three backslashes, that isn't "tripple escaping" it's just two escaped characters: an escaped backslash (\\) followed by an escaped double quote (\").Moustache
@LorneLaliberte Gotcha! I got caught in the argument. Of course, you are right, as I said in the first message :) It is necessary to escape the backslash and the quote which results in three backslashes, which is not tripple escaping.Rubberneck
@Ansell Rather than talk about 'escaping' individual characters, let's talk about 'encoding'. The string in the original post uses JSON encoding. It's a JSON string. In JSON encoding, double quotes in a string are escaped with a backslash. If you want take that string value and plug it into JavaScript, surrounded in single quotes, then need to encode that JSON string as JavaScript string. To encode a JavaScript string, you have to escape the backslashes with backslashes. So there's two levels of encoding necessary for it to be correct.Cowrie
this adds two backslashes, not one, so it's adding an escaped backslack, wenn actually we want to escape the quoteTamar
JSON.parse({"key":"text value \"quoted portion of text value\""}) works just fine, parses into JSON with single quote escape.Retaliate
B
72

When and where to use \\\" instead. OK if you are like me you will feel just as silly as I did when I realized what I was doing after I found this thread.

If you're making a .json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes:\" is the one you're looking for.

However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\". This is because you're building your text string within an HTML <script> block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \" from the standard answer and the JSON parser will parse this as just the double quotes.

<script>
  var text="{";
  text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
  text += "}";
  var obj=JSON.parse(text);
</script>

+1: since it's a JavaScript text string, a double backslash double quote \\" would work too; because the double quote does not need escaped within a single quoted string eg '\"' and '"' result in the same JS string.

Babettebabeuf answered 12/8, 2016 at 16:54 Comment(1)
This solution helps in a Swift version building a string that's added to arguments for a JSON POST.Auguste
L
25

if you want to escape double quote in JSON use \\ to escape it.

example if you want to create json of following javascript object

{time: '7 "o" clock'}

then you must write in following way

'{"time":"7 \\"o\\" clock"}'

if we parse it using JSON.parse()

JSON.parse('{"time":"7 \\"o\\" clock"}')

result will be

{time: "7 "o" clock"}
Lagos answered 14/6, 2017 at 11:49 Comment(3)
This doesn't work for me. I'm on Python with built-in json parser. Which programming language are you using?Homeless
Above code is for javascript not for pythonLagos
Your last example is probably misleading since you do not show the quotes as being escaped. I tested with Firefox, it correctly shows the string as '7 "o" clock' (i.e. using single quote to show a string that includes at least one double quote). It will also switch to backticks if the string include both: single and double quotes. If it includes all three, it uses double quotes and escape the double quotes.Searby
A
20

It's showing the backslash because you're also escaping the backslash.

Aside from double quotes, you must also escape backslashes if you want to include one in your JSON quoted string. However if you intend to use a backslash in an escape sequence, obviously you shouldn't escape it.

Amethyst answered 22/2, 2014 at 15:47 Comment(0)
C
18

tl;dr

If you're inside javascript, python, etc., use raw strings (python's r'' or javascript's String.raw or similar). They make it much easier to write JSON strings because they avoid multiple escape sequence processing.

console.log(JSON.parse(String.raw`"This is a double quote >> \" <<"`))
// => This is a double quote >> " <<

More in depth

Some confusion when writing JSON strings in code comes from string escape sequences being processed multiple times. One time in the programming language, again in the JSON parser (e.g. JSON.parse() in Javascript, or similar)

Use the language's print function to see what escapes are happening in the programming language

It can be confusing to see how strings are displayed in a programming language repl.

E.g. when you type a string directly into a javascript repl, it displays it this way

'Two newlines:\n\nTab here >>\t<<\n\nBackslash here >>\\<<'
// => 'Two newlines:\n\nTab here >>\t<<\n\nBackslash here >>\\<<'

But when you console.log() the string, it displays it this way

console.log('Two newlines:\n\nTab here >>\t<<\n\nBackslash here >>\\<<')
/* =>
Two newlines:

Tab here >> <<

Backslash here >>\<<
*/

When javascript encounters a string, it 'evaluates' the escape sequences before passing it e.g. to a function, in the sense that it replaces each \n with a newline character, each \t with a tab character, etc.

So it helps a lot to console.log() the string to get a better idea of what's going on.

How to encode a single quote in JSON in javascript

To write a " to a JSON in javascript, you could use

console.log(JSON.parse('"This is a double quote >> \\" <<"'));
// => This is a double quote >> " <<

It'd be similar in python and other languages.

Step by step:

  1. javascript evaluates the string using escape sequence rules from the javascript spec, replacing \n with a newline char, \t with a tab char, etc.
    • In our case, it replaces \\ with \.
    • The result string is "This is a double quote >> \" <<"
    • We put the outer double quotes to make it a valid JSON string
  2. javascript takes the result and passes it to the JSON.parse() fn.
  3. JSON.parse evaluates the string using escape sequence rules from the JSON standard, replacing \n with a newline char, \t with a tab char, etc. In our case,
    • the first character it sees is ", so it knows this is a JSON string.
    • Inside the JSON string, it sees \". Normally " would end the JSON string, but because " is escaped with \, it knows this isn't the end of the string and to replace \" with a literal double quote character.
    • the last character it sees is ", so it knows this is the end of the JSON string
    • The result parsed string is This is a double quote >> " <<. Note the outer double quotes are gone also.

Raw strings make things easier

Javascript's String.raw template function and python's r'' strings don't do any escape sequence evaluating, so it makes it much easier and less confusing to reason about

console.log(JSON.parse(String.raw`"This is a double quote >> \" <<"`))
// => This is a double quote >> " <<
Careworn answered 16/3, 2022 at 20:23 Comment(0)
R
12

Note that this most often occurs when the content has been "double encoded", meaning the encoding algorithm has accidentally been called twice.

The first call would encode the "text2" value:

FROM: Heute startet unsere Rundreise "Example text". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.

TO: Heute startet unsere Rundreise \"Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.

A second encoding then converts it again, escaping the already escaped characters:

FROM: Heute startet unsere Rundreise \"Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.

TO: Heute startet unsere Rundreise \\\"Example text\\\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.

So, if you are responsible for the implementation of the server here, check to make sure there aren't two steps trying to encode the same content.

Robins answered 20/11, 2014 at 16:40 Comment(2)
I believe that the encoder would also escape the escape switch so I think your second TO: should read: "Heute startet unsere Rundreise \\\"Example text\\\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.Bucket
@Jonathan Mee: Just edited the answer according to your suggestion. It was theoretically written correctly with 3 backslashes, but stackoverflow also uses backslashes for quoting and converted the 1st two backslashes to one single backslashArty
B
8

To escape backslashes that cause problems for JSON data I use this function.

//escape backslash to avoid errors
var escapeJSON = function(str) {
    return str.replace(/\\/g,'\\');
};
Blooper answered 26/5, 2016 at 15:24 Comment(3)
I would encourage programmers to encode the content, instead of remove (or "cleansing") the content. There used to be this idea of "cleansing" database data -- especially removing single quotes ('). Programmers didn't realize people couldn't use their own last name (O'Doul). I hope programmers of today use other means to get the original content into the database without stripping or cleansing data.Palpitation
Ok I removed the character stripping part to appease the masses. @Palpitation keep in mind stripping text of characters might be the only way to make JS safe in a client app. Angular sanitizes HTML output for this reason by default.Blooper
I agree 100% there are times that data has to be sanitized ... and XSS is one of those times. Thank you for pointing that one out.Palpitation
M
2

For those who would like to use developer powershell. Here are the lines to add to your settings.json:

"terminal.integrated.automationShell.windows": "C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe",
"terminal.integrated.shellArgs.windows": [
    "-noe",
    "-c",
    " &{Import-Module 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\Common7\\Tools\\Microsoft.VisualStudio.DevShell.dll'; Enter-VsDevShell b7c50c8d} ",
    ],
Mishamishaan answered 1/6, 2020 at 21:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.