javascript - How to output JSON parse compatible json with PHP json_encode? JSON.parse - Unexpected token h due to single escaped double quotes -


i have php:

<?php      $jsonarr = array("haha" => array("hihi'hih","hu\"huh"));     print json_encode($jsonarr); 

this gives me

{"haha":["hihi'hih","hu\"huh"]} 

now, in json.parse breaks with

uncaught syntaxerror: unexpected token h     @ object.parse (native) 

, unless double escape backslash this

var json = '{"haha":{"hihi\'hih":"hu\\\"huh"}}'; json.parse(json); 

how can php create json parse compatible output?

meanwhile, did work double json_encoding string in php based on php's json_encode not escape json control characters this, wonder if there other way.

$jsonarr = array("haha" => array("hihi'hih","hu\"huh"));         print json_encode(json_encode($jsonarr)); 

if getting ajax, wouldn't happening, believe you're generating js code using php, this:

var json = '<?php echo $jsonarr; ?>'; var obj = json.parse(json); 

this won't work, because, noted, $jsonarr when printed not have requisite number of backslashes. \" in json needs \\" in js string literal in order understood \".

instead, remember json executable js:

var obj = <?php echo $jsonarr; ?>; 

done!


Comments