imprimir una cadena PHP y analizarla como JSON en javascript

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

Que hago

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

I get a json parse error. What should I be doing?

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]}

preguntado el 28 de agosto de 11 a las 00:08

Just out of curiosity, why call .parseJSON all? Why not just assign the object directly to a variable, since you are outputting directly in the same script anyway? -

@Brad thank you that works :-) . but then I am confused myself, why would I use $.parseJSon then? -

@SAnandNarayan: you'd use parseJSON when you for example get it from the server with AJAX. -

2 Respuestas

I think JSON parsers don't like line breaks in strings for some reason. Parsing worked for me after removing the \u000a characters.

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

Respondido 28 ago 11, 04:08

From your example, it appears like you're trying to insert PHP code into your javascript. You can't use PHP like that. PHP is server side, while Javascript runs in the browser after the page has been downloaded.

If you must get data from PHP to your javascript, you need to use AJAX. It's actually really easy with JQuery. Check out http://api.jquery.com/jQuery.ajax/

Respondido 28 ago 11, 04:08

You can use PHP to generate anything you want, including JavaScript. - Brad

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.