0

I have this 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 this breaks with

Uncaught SyntaxError: Unexpected token h
    at Object.parse (native)

, unless I double escape the backslash like this

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

How can I get php to create a JSON parse compatible output?

Meanwhile, I did get this to work with double json_encoding the string in php based on this PHP's json_encode does not escape all JSON control characters like this, but wonder if there is some other way.

$jsonarr = array("haha" => array("hihi'hih","hu\"huh"));
        print json_encode(json_encode($jsonarr));
Community
  • 1
  • 1
giorgio79
  • 3,787
  • 9
  • 53
  • 85
  • 1
    Are you getting this from AJAX, or embedding in the page? (I believe embedding in the page; if so, don't `JSON.parse`. You're breaking it, not `json_encode`.) – Amadan Jul 10 '15 at 08:29
  • I am accessing a php json_encoded file on my server from a Google Apps script, and there I can fetch that file as a string. So, I must do a JSON parse to get it into an object. – giorgio79 Jul 10 '15 at 08:46

1 Answers1

3

If you were getting this from AJAX, it wouldn't be happening, so I believe you're generating JS code using PHP, something like this:

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

This won't work, because, as you noted, $jsonarr when printed will not have the requisite number of backslashes. \" in JSON needs to be \\" in a JS string literal in order to be understood as \".

Instead, remember that JSON is executable JS:

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

Done!

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • I am accessing a php json_encoded file on my server from a Google Apps script, and there I can fetch that file as a string. So, I must do a JSON parse to get it into an object. – giorgio79 Jul 10 '15 at 08:45
  • If you have a JSON string in PHP, you can just print it as JS *code* into your page, no `JSON.parse` needed, as long as you're letting PHP generate your page for you. – Amadan Jul 10 '15 at 08:46