[Solved-4 Solutions] Parsing JSON giving “unexpected token o” error



Error Description:

    • We get problems in parsing simple JSON strings. When we check them on JSONLint, it shows that they are valid. But when we try to parse them using either JSON.parse or the jQuery alternative it gives us the 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>
    
    click below button to copy the code. By - JavaScript tutorial - team

    Solution 1:

      • Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.
      var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
      document.write(cur_ques_details['ques_title']);
      
      
      click below button to copy the code. By - JavaScript tutorial - team

      Solution 2:

        • Try parse :
        var yourval = jQuery.parseJSON(JSON.stringify(data));
        
        click below button to copy the code. By - JavaScript tutorial - team

        Solution 3:

          • cur_ques_details is already a JS object, you don't need to parse it

          Solution 4:

            • The source of your error, however, is that you need to place the full JSON string in quotes. The following will fix your sample:
            <!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>
            
            click below button to copy the code. By - JavaScript tutorial - team
            • The object is already parsed into a JS object so you don't need to parse it. To demonstrate how to accomplish the same thing without parsing, you can do the following:
            <!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>
            
            
            click below button to copy the code. By - JavaScript tutorial - team

            Related Searches to Parsing JSON giving “unexpected token o” error