Analizar JSON dando "token inesperado o" error [duplicado]


Esta pregunta ya tiene una respuesta aquí:

Tengo un problema al analizar cadenas JSON simples. Los he comprobado en JSONLint y muestra que son válidos. Pero cuando intento analizarlos usando JSON.parse o la alternativa de jQuery, me da el error unexpected token o:

<!doctype HTML>
<html>
  <head>
  </head>
  <body>
    <script type="text/javascript">
      var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
      var ques_list = JSON.parse(cur_ques_details);

      document.write(ques_list['ques_title']);
    </script>
  </body>
</html>

Nota: Estoy codificando mis cadenas usando json_encode() en PHP.

Author: Li357, 2013-03-25

8 answers

Sus datos ya son un objeto. No hay necesidad de analizarlo. El intérprete de javascript ya lo ha analizado por usted.

var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details['ques_title']);
 600
Author: Dark Falcon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-25 14:17:54

Intenta analizar así:

var yourval = jQuery.parseJSON(JSON.stringify(data));
 57
Author: Юрий Шпакович,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-14 15:32:37

cur_ques_details ya es un objeto JS, no es necesario analizarlo

 10
Author: Shuping,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-25 14:51:57

Usando JSON.stringify(data);:

$.ajax({
    url: ...
    success:function(data){
        JSON.stringify(data); //to string
        alert(data.you_value); //to view you pop up
    }
});
 9
Author: Iyes boy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-08 02:08:54

La fuente de su error, sin embargo, es que necesita colocar la cadena JSON completa entre comillas. Lo siguiente arreglará su muestra:

<!doctype HTML>
<html>
    <head>
    </head>
    <body>
        <script type="text/javascript">
            var cur_ques_details ='{"ques_id":"15","ques_title":"jlkjlkjlkjljl"}';
            var ques_list = JSON.parse(cur_ques_details);
            document.write(ques_list['ques_title']);
        </script>
    </body>
</html>

Como los otros encuestados han mencionado, el objeto ya está analizado en un objeto JS, por lo que no es necesario analizarlo. Para demostrar cómo lograr lo mismo sin analizar, puede hacer lo siguiente:

<!doctype HTML>
<html>
<head>
</head>
    <body>
        <script type="text/javascript">
            var cur_ques_details ={"ques_id":"15","ques_title":"jlkjlkjlkjljl"};
            document.write(cur_ques_details.ques_title);
        </script>
    </body>
</html>
 9
Author: PlantationGator,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-12 04:11:39

La respuesta ya está analizada, no es necesario analizarla de nuevo. si lo analizas de nuevo, te dará " unexpected token o". si necesita obtenerla como cadena, puede usar JSON.stringify()

 5
Author: msoliman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-29 20:54:29

Tuve el mismo problema cuando envié datos usando jQuery AJAX:

$.ajax({
   url:...
   success:function(data){
      //server response's data is JSON
      //I use jQuery's parseJSON method 
      $.parseJSON(data);//it's ERROR
   }
});

Si la respuesta es JSON, y usa este método, los datos que obtiene son un objeto JavaScript, pero si usa dataType:"text", los datos son una cadena JSON. Entonces el uso de $.parseJSON está bien.

 4
Author: Saber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-08 01:39:39

Estaba viendo este error unexpected token o porque mi código (incompleto) se había ejecutado previamente (live reload!) y establezca el valor de almacenamiento local con clave particular en [object Object] en lugar de {}. No fue hasta que cambié las llaves, que las cosas comenzaron a funcionar como se esperaba. Alternativamente, puede seguir estas instrucciones para eliminar el valor de localStorage incorrectamente establecido.

 0
Author: alexkb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:40