Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put double quotes inside a string within an ajax JSON response from php?

I receive a JSON response in an Ajax request from the server. This way it works:

{ "a" : "1", "b" : "hello 'kitty'" }

But I did not succeed in putting double quotes around kitty.

When I convert " to \x22 in the Ajax response, it is still interpreted as " by JavaScript and I cannot parse the JSON.

Should I also escape the \ and unescape later (which would be possible)?

How to do this?

Edit: I am not sure if i expressed it well: I want this string inside of "b" after the parse:

hello "kitty"

If necessary I could also add an additional step after the parse to convert "b", but I guess it is not necessary, there is a more elegant way so this happens automatically?

Edit2: The ajax page is generated by php. I tried several things now to create the value of b, all result in JSON parse error on the page:

  $b = 'hello "kitty"';          // no 1:   //$b = str_replace('"',"\x22",$b);    // or no 2:   // $b = addslashes($b);      // or no 3:    $b = str_replace('"','\"',$b);    echo '{ "a" : "1", "b" : "' . $b . '"}'; 

Edit3: This solution finally works:

$b = 'hello "kitty"';       $b = str_replace('"','\\"',$b);  echo '{ "a" : "1", "b" : "' . $b . '"}'; 
like image 670
user89021 Avatar asked Apr 28 '10 19:04

user89021


People also ask

How do I pass a string with double quotes in JSON?

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

Can you use a double quote inside a JSON string?

Can you use a double quote inside a JSON string? Yes, if you use the ascii code.

How do you pass a double quote in a string?

To place quotation marks in a string in your code In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark.

Do you need double quotes in JSON?

JSON names require double quotes.


2 Answers

Just escape it with a backslash:

> JSON.stringify({"a": 5, "b": 'a "kitty" mighty odd'}) {"a":5,"b":"a \"kitty\" mighty odd"} > JSON.parse('{"a":5,"b":"a \\"kitty\\" mighty odd"}') Object   a: 5   b: a "kitty" mighty odd   __proto__: Object 

JSON parsers recognize \" inside double-quoted strings as a double quote. Note that in the second example, the double-backslash is needed because there's a Javascript parser pass, then another JSON parser pass.

like image 189
Max Shawabkeh Avatar answered Oct 12 '22 05:10

Max Shawabkeh


use just json_encode (any PHP element ), it will automatically parses.

like image 37
mahesh Avatar answered Oct 12 '22 04:10

mahesh