1

Here is my PHP array:

$entries = array(
    1420934400 => array(
        'entry' => 'I think I liked it.',
        'data' => 'some'
    ),
    1452470400 => array(
        'entry' => 'Turkey is much better. Tastes more like chicken.',
        'data' => 'no calls'
    ));

Then I convert to JSON

$entries = json_encode($entries);

This produces the string:
{"1420934400":{"entry":"I think I liked it.","data":"some"},"1452470400":{"entry":"Turkey is much better. Tastes more like chicken.","data":"no calls"}}

...which I believe is valid JSON. But when I try to access in JavaScript:

<script>
    var fetchedEntries = JSON.parse(<?php echo $entries ?>);
    console.log('entries: %o', fetchedEntries);
</script>

I get the following error:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

Can anyone see where I'm going wrong?

1
  • 1
    If for some reason you wanted to parse a string, which as noted in the answer below isn't really neccessary, you'd have to quote it with single quotes, so it's JSON.parse('<?php echo $entries ?>'); Commented Dec 11, 2015 at 20:08

1 Answer 1

7

You don't need JSON.parse in JS since JSON can be directly interpreted by JS (it is called JavaScript Object Notation for a reason ;-). Do

var fetchedEntries = <?php echo $entries ?>;

When you receive the JSON data as a string, then JSON.parse is appropriate. For example, this works too:

var fetchedEntries = JSON.parse( "<?php echo json_encode( $array_or_obj ); ?>" );
Sign up to request clarification or add additional context in comments.

2 Comments

Doh indeed. Just out of curiosity, when would JSON.parse be required?
:-) In short, when you get a JSON string, from AJAX for instance. Updated the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.