bicccio
bicccio

Reputation: 394

javascript/php single quote

i'm trying to this:

<?php $php_array = array ('var1' => "l'ape"); ?>

<script type="text/javascript">
var my_javascript_object = jQuery.parseJSON('<?php echo json_encode($php_array); ?>');
</script>

I got this error "Uncaught SyntaxError: Unexpected identifier". The problem is the single quote in the value of var1 in $php_array.

This doesn't work

 <?php $php_array = array ('var1' => "l\'ape"); ?>

Upvotes: 1

Views: 513

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318518

The problem is that you try to put the JSON in a JavaScript string.

Do this instead:

var my_js_obj = <?php echo json_encode($php_array); ?>;

A JSON string is a valid JavaScript expression which you can simply put directly in your JS code.


If you really wanted to create a string containing JSON (you don't!), you'd do it like this:

var my_json_string = <?php echo json_encode(json_encode($php_array)); ?>;
var my_js_obj = $.parseJSON(my_json_string);

Upvotes: 2

Paul
Paul

Reputation: 141827

You don't need to parse your with JSON.parse in this case. Just use it as an object literal instead of a Javascript string:

var my_javascript_object = <?php echo json_encode($php_array); ?>;

Upvotes: 3

Related Questions