I'm having trouble with embedding json in my website.

This is html and javascript:

<!doctype html>
<html lang="us">
<head>
    <meta charset="utf-8">
    <title>jQuery UI Example Page</title>
    <link href="css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet">
    <script src="js/jquery-1.9.0.js"></script>
    <script src="js/jquery-ui-1.10.0.custom.js"></script>
    <script>

    function isJSON(str) {
        try {
            JSON.parse(str)
        } catch (e) {
            return false
        }
        return true
    }

    jQuery(function(){

        <?
            $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
        ?>

        data = <?= json_encode($arr) ?>

        if (isJSON(data)) {
            json = jQuery.parseJSON(data)
            console.log(json)
        } else {
            console.log("Not a json.")
            console.log(data)
            console.log(jQuery.parseJSON(data))
        }

    })


    </script>

<body>


</body>
</html>

This outputs in console the following:

Not a json. filename.php:29
Object {a: 1, b: 2, c: 3, d: 4, e: 5} filename.php:30
Uncaught SyntaxError: Unexpected token o 

Been a long day already and most probably (hopefully) I'm missing something obvious. I tried validate the generated json here: http://jsonlint.com/ and according to their site it was valid.

Thanks in advance!

share|improve this question
1  
Avoid using PHP short tags. – BenM Feb 14 at 15:44
@BenM Why? - I've never had problems with them. – krabats Feb 14 at 15:48
@krabats: They're not enabled by default on all servers. – cdmckay Feb 14 at 15:49
Portability, as @cdmckay indicated. Much safer to use <?php echo ... ?> – BenM Feb 14 at 15:50
@BenM thanks for caring to point this out but this is plain wrong. Been working with many servers and never had problems with short tags not being enabled. And on top of that: php.net/manual/en/function.echo.php since php 5.4.0 short echo is now official part of php regardless of php.ini configuration. – krabats Feb 14 at 16:08
show 4 more comments

3 Answers

up vote 2 down vote accepted

JSON is (more or less) a JavaScript literal.

If you dump it into a script, you don't need to parse it at all.

var data = <?php echo json_encode($arr); ?>;
console.log(data);

If you want something to pass to jQuery.parseJSON then you need to generate a JavaScript string containing JSON, not plain JSON.

share|improve this answer
In case it's not clear, after PHP runs the first line will look like var data = {"a":1,"b":2,"c":3,"d":4,"e":5}. If you view source you should see that now. – cdmckay Feb 14 at 15:50
The issue was in a different piece of code but your post pushed me in the right direction. Thanks! – krabats Feb 14 at 17:00

Maybe you can look at this example

var object = {}
object.text = "Hello World!"

var json = JSON.stringify(object)
alert(json)

var object = JSON && JSON.parse(json) || $.parseJSON(json)
alert(object.text)

Jsfiddle link

share|improve this answer

There are two issues I see here (in addition to using PHP short tags). First, you're missing semicolons at the end of all lines. And second is in line

data = <?= json_encode($arr) ?>;

This will produce something like:

data = {"a": 1, "b": 2, ...};

This is already a decoded object. You can't then json_decode it again. And there's no need to do so. If you insist on json_decodeing it, then you need to output it as a string:

data = "<?= str_replace("\"", "\\\"", json_encode($arr)) ?>";

This will produce something like this:

data = "{\"a\": 1, \"b\": 2, ...}";

Now your data contains a string, which can be json_decoded.

share|improve this answer
The JSON-encoded object will have double-quotes around the object keys. – cdmckay Feb 14 at 15:51
@cdmckay Yes, I think you're right, I'll update the answer. However in this case it makes no difference. – Aleks G Feb 14 at 15:53
semicolons in JS are optitional – krabats Feb 14 at 16:11
2  
@krabats: That's not always true: blog.magnetiq.com/post/493356934/… – cdmckay Feb 14 at 16:34
@cdmckay you're right about that one but most of the time its handy I dont have to write them – krabats Feb 14 at 17:05

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.