user3365404
user3365404

Reputation: 61

PHP json_encode return unescaped '

I experience the problem with parsing json encoded object in js. JSON.parse(word_array); with error Uncaught SyntaxError: Unexpected identifier

My investigation showed that object word_array does not exist because of wrong-formation in PHP: it has a unescaped single quote' inside, thus making js consider it as the end of the string.

I form encoding next way:

echo "<script>var word_array = '";
echo  json_encode($word_set);
echo "';\n";

As far as I know, json_encode should escape all undesirable charactets like ' but it does not. What might be the problem?

My php version: Version PHP: 5.3.13 And $word_set is array of assoc. array:

$word_set = array();
while($stmt->fetch())
{
  $word_set_tmp[] = array(
    'word' => $word, 
    'definition' => $def
  );
  array_push ($word_set,$word_set_tmp);
} 

Upvotes: 0

Views: 375

Answers (1)

Steve
Steve

Reputation: 20469

The problem is you surrounding an array declaration in single quotes, remove them and all is well:

echo "<script>var word_array = " . json_encode($word_set) . ";";

As a side note, i find when i must mix php with anything else (html, js) then its best to exit php mode and write html/js, echoing out the required php vars, rather than echo out html/js:

<?php 
    $word_set = $db->somfunc();
?>
<script>
    var word_array="<?php echo json_encode($word_set);?>";
    alert(word_array[1].definition);
</script>

Upvotes: 5

Related Questions