views:

152

answers:

1

Hi

I'm using the combination of json_encode (PHP) and JSON.parser (Javascript from json.org) for passing a JSON object from PHP to Javascript, the JSON object may have quotes and double quotes so I'm using addslashes() function in PHP. This combination work well in Firefox but not in other browsers like Safari, Chrome or Internet Explorer. This is the code:

<?php

   $json =array('n' => count($arrayEx), 'items' => array());

   foreach($arrayEx as $item)
   {
      $json['items'][]=array( 'property1' => addslashes($item['property1']),
                     'property2' =>addslashes($item['property2'])
                            );

   }    

   $json_string = json_encode($json);

?>

<script>    
   var json_string= '<? echo $json_string; ?>'; 
   var json_object = JSON.parse(json_string);   //Fail in this line
</script>

Fail with error message "String literal not ended".

Thanks

+1  A: 

Leave the quotes out and it should work:

var json_string = <?php echo $json_string; ?>;

The string returned by json_encode already is a valid JavaScript expression and thus doesn’t need any further declarations.

Gumbo
Thanks that's work for me and you answer me quickly, but i'm thinking about this and now i'm a little bit confused about what is the right scenario for use JSON.parse().
hcentelles
@hcentelles: Ah, yes. `JSON.parse()` is only used if the JSON data is a string, e.g. the response of an Ajax request. But in your example `json_string` already is an object.
Gumbo