M
M
miniven2016-04-20 10:55:07
JavaScript
miniven, 2016-04-20 10:55:07

Uncaught SyntaxError: Unexpected token on parseJSON(). How to fix?

Write data from php (Laravel) to js variable.

var objects = "{{json_encode($objects)}}";
  objects = objects.replace(/"/g,'"');

Everything is fine here, I get a json format string
Then I want to make this string an object and output it to the console:
console.log(jQuery.parseJSON(objects));
I get
VM3905:1 Uncaught SyntaxError: Unexpected token
What's the problem? How to fix? What did he do wrong?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Ukolov, 2016-04-20
@miniven

There is no need to escape data when outputting, and everything will work without crutches with replace.
And if you do not wrap it in quotes, then you won’t need to parse it later - after all, json_encode immediately returns valid js.
var objects = {!! json_encode($objects) !!};

P
Peter, 2016-04-20
@petermzg

"{{json_encode($objects)}}" - this definitely doesn't match the json format

E
Eugene, 2016-04-20
@Nc_Soft

<script type="application/json" id="json">{"json_data":"here"}</script>
<script>
$(function(){
    var json = JSON.parse($('#json').text());
});
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question