Sto avendo un problema nell'analizzare semplici stringhe JSON. Le ho controllate su JSONLint e mostra che sono valide. Ma quando provo ad analizzarle usando JSON.parse
o l'alternativa jQuery mi dà l'errore 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: sto codificando le mie stringhe usando json_encode()
in PHP.
I vostri dati sono già un oggetto. Non c'è bisogno di analizzarli. L'interprete javascript li ha già analizzati per voi.
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details['ques_title']);
La fonte del tuo errore, tuttavia, è che hai bisogno di mettere la stringa JSON completa tra virgolette. Il seguente aggiusterà il tuo campione:
<!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>
Come gli altri intervistati hanno menzionato, l'oggetto è già analizzato in un oggetto JS quindi non hai bisogno di analizzarlo. Per dimostrare come realizzare la stessa cosa senza fare il parsing, puoi fare quanto segue:
<!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>