Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JSON String, escape Double Quotes for JS output

I'm creating a JSON string from a PHP array. I've encoded it using json_encode().

$data = array(     'title' => 'Example string\'s with "special" characters' );  $data = json_encode( $data ); 

$data is localized using wp_localize_script() and is accessible via a global data variable.

In the JS file I can access the information by the following:

var data     = data.replace( /"/g, '"' ),     jsonData = jQuery.parseJSON( data );  console.log( jsonData ); 

This results in an output of:

{ "title":"Example string's with "special" characters" } 

Entering that result into http://jsonlint.com/ returns an error. Removing the double quotes around "special" validates the string.

What is the best way to create a JSON string from PHP and properly escape it for use in a JS file?

like image 293
Luke Avatar asked Sep 18 '11 15:09

Luke


People also ask

How do I ignore 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?

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

How do you escape quotes in PHP?

In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.


2 Answers

Another way would be to encode the quotes using htmlspecialchars:

$json_array = array(     'title' => 'Example string\'s with "special" characters' );  $json_decode = htmlspecialchars(json_encode($json_array), ENT_QUOTES, 'UTF-8'); 
like image 193
Danny Thompson Avatar answered Sep 20 '22 04:09

Danny Thompson


I succefully just did this :

$json = str_replace("\u0022","\\\\\"",json_encode( $phpArray,JSON_HEX_QUOT));  

json_encode() by default will escape " to \" . But it's still wrong JSON for json.PARSE(). So by adding option JSON_HEX_QUOT, json_encode() will replace " with \u0022. json.PARSE() still will not like \u0022. So then we need to replace \u0022 with \\". The \\\\\" is escaped \\".

NOTE : you can add option JSON_HEX_APOS to replace single quote with unicode HEX value if you have javascript single quote issue.

ex: json_encode( $phpArray, JSON_HEX_APOS|JSON_HEX_QUOT ));

like image 27
Grégoire Lafortune Avatar answered Sep 24 '22 04:09

Grégoire Lafortune