Print a PHP string and parse it as JSON in javascript

I have json_string in my database. I echo and parse it on an object in javascript

I do

$.parseJSON('<?php echo $json_string;?>'); 

I get json parsing error. What should I do?

This is my json_String

 {"patches":[[{"diffs":[[1,"\u000a\u000a printhellon() {\u000a\u000a\u000a}d\u000a\u000a\u000a"]],"start1":0,"start2":0,"length1":0,"length2":26}],[{"diffs":[[0,") {\u000a\u000a\u000a}d"],[1,"s"],[0,"\u000a\u000a\u000a"]],"start1":15,"start2":15,"length1":11,"length2":12}],[{"diffs":[[0," {\u000a\u000a\u000a}ds"],[1,"d"],[0,"\u000a\u000a\u000a"]],"start1":16,"start2":16,"length1":11,"length2":12}]],"times":[1314489779299,1314489779408,1314489779581]} 
+4
source share
2 answers

I think that JSON parsers for some reason don't like line breaks in lines. After removing the characters, \ u000a worked for me.

Edit: as Brad said, it would be better to include the code directly as an object. JSON parsing is usually more useful for data retrieved using Ajax or something else.

+5
source

In your example, it looks like you are trying to embed PHP code in your javascript. You cannot use such PHP. PHP is server-side, and Javascript runs in the browser after the page loads.

If you need to get data from PHP to your javascript, you need to use AJAX. It is really very simple with jQuery. Check out http://api.jquery.com/jQuery.ajax/

-3
source

Source: https://habr.com/ru/post/1369334/


All Articles