Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape double quotes in JSON

Tags:

json

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?

like image 498
user1937021 Avatar asked Mar 26 '13 12:03

user1937021


People also ask

How do I ignore double quotes in JSON?

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

How do you escape a double quote?

If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.

Does JSON accept double quotes?

JSON stands for Javascript Object Notation and is a convenient and human-readable way to represent data. There are three basic types of data that can be represented in JSON, which are strings, numbers, and booleans. Strings should always use double quotes: "this is a string" .


2 Answers

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).

like image 179
kamituel Avatar answered Oct 27 '22 07:10

kamituel


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.

like image 20
Gregor y Avatar answered Oct 27 '22 08:10

Gregor y